Tuesday, 17 September 2013

Volatile and Synchronized in Java

Volatile is just another modifier like private , protected etc. It modifies the visibility of the variables and is generally more relevant in thread context.

Volatile when used on a variable ensures that every thread that is using it has the latest copy. It is important in multi threaded programming that shared variables which are frequently read and write by the threads are marked as volatile.
JVM is free to do anything with the variables and every thread can, actually does keep its own copy of variable meaning if a thread writes a new value to a variable, the other thread wont get that latest value. Hence the volatile.

private int x  = 5;  
Thread 1 uses it and makes it 8, but thread 2 will have its own copy as 5 and wont see new value 8.
This can of course leads to a lot of problems and i don't think there is any need to explain that.
Primary three reasons to use volatile when needed:

1. Every thread keeps it own copy of a variable, so if you want a shared variable with publish sort of functionality i.e. that every where its latest value is used, make it volatile.
2. CPU caches : if the variable is cached it isn't necessary that that value will be updated which could lead some odd values with some threads. Hence volatile :).
3. Volatile ensures that all the operations happening on that variable are atomic. For eg changing a Long value is actually two write operations than one. If that variable is not volatile it might happen that when one thread was in middle of process of modifying that variable , some other thread accessed it and got some arbitrary value since write operation was not complete. The volatile keyword ensures that before any other thread reads that value, the write operations are completed.


Synchronized is used to achieve locks on variables which are supposed to be accessed by the different threads. Where volatile ensures every thread has the latest value, it fails to maintain the write operation or perhaps the sequence of write operations done on  a variable. This is where synchronized comes into play.
Synchronized should be implemented properly. Instead of making whole class synchronized , the actual data structures should be identified which needs to be synchronized and should be synchronized. However in some cases when that data structure is in use everywhere avoiding synchronizing every class methods is the only option.

Will write more on synchronized after i read more about it ...!! 

No comments:

Post a Comment