long and double assignments are not atomic - How does it matter?

前端 未结 3 1641
-上瘾入骨i
-上瘾入骨i 2021-02-10 17:07

We know that long and double assignments are not atomic in Java until they are declared volatile. My question is how does it really matter in our programming practice. for inst

3条回答
  •  臣服心动
    2021-02-10 17:27

    It makes a difference if SharedInt or SharedLong are going to be accessed simultaneously. As you said, one thread may read a stale int, or a stale or corrupted long.

    This could be important if the value was being used to reference an array.

    Or with display in a GUI.

    How about writing some values over a network and sending bad data. Now clients are confused or crashing.

    Incorrect values could be stored to a database.

    Repeated calculations could be corrupted...

    As you requested in comments, For long specifically:

    Long values are frequently used for time calculations. This could throw off loops where you are waiting for an amount of time before performing some operation, such as a heartbeat in a networking app.

    You could report to a client synchronizing clocks with you time was 80 years or 1000 years in the past.

    Longs and ints are commonly used for bitpacked fields to indicate many different things. Your flags would be entirely corrupted.

    Longs are used as unique ID's frequently. This could corrupt hash tables you're creating.

    Obviously lots of bad, bad stuff could happen. If this value needs to be thread safe, and you want your software to be very reliable, declare these variables volatile, use an Atomic variable, or synchronize access and set methods.

提交回复
热议问题