Login with  Log in with facebook
Hiring Manager? SIGN UP HERE

If I declare shared state volatile in Java, do I really need to care about Thread Safety?

Rishi Yadav
08/10/2011 at 22:47
4 Answers

Answer is no. Volatile means that the value of variable is not read from registers but from main memory and that removes data corruption chances due to multithreading. 


Rishi Yadav
08/13/2011 at 18:46


Even if we declare a state variable as volatile, it is not thread safe. concurrent access to the volatile variable is always possible. i.e. it does not have the mutual exclusion, which is achieved with synchronized. only the read and write are of volatile is atomic, but operators like +=  are not atomic.


Pravin Jain
08/27/2011 at 11:14


and also volatile variables will not be optimized by compiler rite?

Vinay Goli
08/18/2011 at 22:16


The only difference between volatile variable and instance variable is that rights to volatile memory are directly updated into main memory and hence is instantaneously available to all other threads which is not the case with instance variable. Any updated to instance variable from one thread will be visible to other threads only once the updates are flushed to main memory which may happen at a later point.


One thing to note however is that writes to volatile variables will not be atomic.


volatile int a=0;



between steps 1 and 2 it may be possible that another thread updated the value of a.

Thomas Eapen
08/20/2011 at 00:50

If you want to post any answer to this forum then you need to log in.
Schedule a Demo

Schedule a Demo with us

Name *
Email *
Phone *
Company *