multithreading - Java - is volatile required with synchronized? -


in following simple scenario:

class {   int x;   object lock;    ...    public void method(){     synchronized(lock){       // modify/read x , act upon value     }   } } 

does x need volatile? know synchronized guarantees atomicity, not sure visibility though... lock -> modify -> unlock -> lock guarantee, after second lock value of x "fresh"?

no not, synchronised has memory barrier inserted after it, threads see update current thread performs, taking account other threads synchronise on same lock.

volatile, synchronised has memory barriers attached - depending on cpu store/load/full barrier ensures update 1 thread visible other(s). i assume performed cpu cache invalidation.

edit i've read, store buffers flushed cpu cache, , how visibility achieved.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -