Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using volatile keyword in java4 and java5

Tags:

java

what is the difference in using volatile keyword in java4 and java5 onwards?

and related to that,

Read/write operations on non-atomic variables(long/double) are atomic when they are declared as volatile.

Is this also true for java4 or it is valid from java5 onwards???

like image 639
a Learner Avatar asked Apr 26 '12 14:04

a Learner


People also ask

How is a volatile keyword used in Java?

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.

When should I use volatile in Java?

Yes, volatile must be used whenever you want a mutable variable to be accessed by multiple threads. It is not very common usecase because typically you need to perform more than a single atomic operation (e.g. check the variable state before modifying it), in which case you would use a synchronized block instead.

Can we use static and volatile together in Java?

Yes, you can. A static variable in Java is stored once per class (not once per object, such as non-static variables are). This means all your objects (and static methods) share the same variable.


2 Answers

Yes there is a difference.
Up to Java 4 volatile could be re-ordered by compiler with respect to any previous read or write, leading to subtle concurrency bugs e.g. making it impossible to implement a double check locking (very common idiom for a Singleton).
This is fixed in Java 5.0 which extends the semantics for volatile which cannot be reordered with respect to any following read or write anymore and introduces a new memory model. You can read this Double Checked Locking for example reference

like image 104
Cratylus Avatar answered Sep 20 '22 10:09

Cratylus


This site gives a good explanation of the differences: http://www.javamex.com/tutorials/synchronization_volatile.shtml

They also give an explanation of the behavior of volatile in Java 5 on a separate page: http://www.javamex.com/tutorials/synchronization_volatile_java_5.shtml

like image 21
Rens Verhage Avatar answered Sep 22 '22 10:09

Rens Verhage