multithreading - Java When using synchronized do I get volatile functionality for free? -


i read several posts concurrency problems i'm still unsure something. can when using synchronized, volatile functionality free, because when lock on object released, next thread reads modified object. volatile, value of object reflected other threads. when use synchronized, there no possibility reflect due lock on object. when lock released, thread may access it. don't have care reflecting value other threads. understand right?

[update]
example prints 1 2 3 4 5 6 7 8 9 without volatile.

package main;  public class counter {     public static long count = 0; }  public class usecounter implements runnable {     public void increment()     {         synchronized (this)         {                    counter.count++;             system.out.print(counter.count + " ");         }     }      @override     public void run()     {         increment();         increment();         increment();     } }  public class datarace {     public static void main(string args[])     {         usecounter c = new usecounter();          thread t1 = new thread(c);         thread t2 = new thread(c);         thread t3 = new thread(c);          t1.start();         t2.start();         t3.start();     } } 

no, volatile access not implied synchronized access according the java memory model (although on particular implementations, may be, should not depend on that)

java language specification 17.4.4 (on java memory model):

synchronization actions induce synchronized-with relation on actions, defined follows:

  • an unlock action on monitor m synchronizes-with subsequent lock actions on m (where "subsequent" defined according synchronization order).

  • a write volatile variable v (§8.3.1.4) synchronizes-with subsequent reads of v thread (where "subsequent" defined according synchronization order).

volatile operates on variable , synchronized operates on monitor (the 'lock') of object.

if 1 thread has exited synchronized block on object o, , thread b has read volatile variable (instance field) v on object o, there still not synchronized-with relation between 2 threads. there no guarantee thread see data modifications done thread b or vice versa, until thread b synchronized on object o, or until thread accessed volatile field v on object o.


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -