Thursday, December 10, 2009

Volatile keyword

Volatile

Synchronized block accepts only objects, how do I synchronize primitive data types. We can not go with Wrapper classes like Integer, Double, since these classes are the immutable. Each new value assigned to variable of these wrapper class objects, creates new objects.

Generally, each thread will take it own copy of the value and operates and stores back to the original address of the variable (means, caching the value in thread and stores back to the actual location). Run the following code, in very rare condition, we will see duplicate numbers and/or maximum number will be less than 100. If this issue araised in customer place, then we may go mad and talk to manager saying that it is not possible to reproduce in our environment. In lighter side, you may get travel to customer place or relatively pink notice ;)


import java.util.ArrayList;
import java.util.List;

public class VolatileIncrement {
int x = 0;
public void f() { x++; }
public String toString() { return Integer.toString(x); }
public static void main(String[] args) {
final VolatileIncrement vi = new VolatileIncrement();
List<Thread> threads=new ArrayList<Thread>();
for(int i=0;i<100;i++)
{
Thread t1 = new Thread() {
@Override
public void run() {
vi.f();
System.out.println(vi);
}
};

threads.add(t1);
}
for(Thread t:threads)
{
t.start();
}

}
}

volatile is the keyword which tells to threads that MUST operate with the actual address, instead of caching. We are get gauranteed to get always solid result in multithreaded environment for the primitive data types.

volatile int x=0;


what could be the differences of volatile and synchronized keywords

volatile - operates on primitive data type, no thread safe possible for block of code or method
synchronized - operates on block of code or method, thread safe for block code and its objects

No comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com