Quantcast
Channel: long and double assignments are not atomic - How does it matter? - Stack Overflow
Viewing all articles
Browse latest Browse all 4

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

$
0
0

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 instance if you the see below classes whose objects are being shared among multiple threads.

/***  The below class is not thread safe. the assignments to int values would be *  atomic but at the same time it not guaranteed that changes would be visible to *  other threads.**/public final class SharedInt {   private int value;   public void setValue(int value) {      this.value = value;   }   public int getValue() {      return this.value;   }}

Now consider another SharedLong

/*** The below class is not thread safe because here the assignments to  long *  are not atomic as well as changes are not*  guaranteed to be visible to other threads.*/public final class SharedLong {    private long value;    public void setValue(long  value) {      this.value = value;    }    public long getValue() {       return this.values;    }}

Now we can see the both of the above versions are not thread safe. In case of int, it is because threads may see stale values of integer. While in case if long, they can see corrupt as well as stale values of long variable.

In both cases, if an instance is not shared among multiple threads, then the classes are safe.

To make the above classes thread safe we need to declare int and long both to be volatile or make the method synchronized.This make me wonder: How does it really matter if assignments to long and double are not atomic during our normal course of programming because both need to be declared volatile or synchronized for multithreaded access so my Questions is What are the scenarios where the fact that long assignments are not atomic may make a difference?.


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images