I understand the volatile keyword in Java can make the read/write operations of reference variables and all primitives except long and double, atomic in nature.
I also know compound statements such as incrementing an integer, var++, are not atomic and should not be used in place of synchronized statements.
But what about this class?
public class Setter{
private int num = 0;
public int setNum(int numIn){
num = numIn;
return num;
}
}
Now say you declare an instance of Setter as volatile.
public class Main {
private volatile Setter s;
public static void main(String[] args){
s = new Setter();
s.setNum(5);
}
}
Is a call to the method setNum atomic? Is this statement safe if multiple threads are calling it at once, each with different values?
What would be an example of using a volatile class in a proper way, and using it in an unsafe compound statement?
Is a call to the method setNum atomic?
No, it's not. It is only the reads / writes to s
that would be volatile.
This can be compared with letting a List
be final
. This is not sufficient to make the list immutable, only the list-reference itself.