multithreading - How Often Will Java Sync To Main Memory? -


i have set of counters ever updated in single thread.

if read these values thread , don't user volatile/atomic/synchronized how out of date can these values be?

i ask wondering if can avoid using volatile/atomic/synchronized here.

i believe can't make assumptions time update (so forced use @ least volatile). want make sure not missing here.

i ask wondering if can avoid using volatile/atomic/synchronized here.

in practice, cpu cache going synchronized main memory anyway on regular basis (how depends on many parameters), sounds able see new values time time.

but missing point: actual problem if don't use proper synchronization pattern, compiler free "optimise" code , remove update part.

for example:

class broken {     boolean stop = false;      void broken() throws exception {         while (!stop) {             thread.sleep(100);         }     } } 

the compiler authorised rewrite code as:

void broken() throws exception {     while (true) {         thread.sleep(100);     } } 

because there no obligation check if non-volatile stop might change while executing broken method. mark stop variable volatile , optimisation not allowed more.

bottom line: if need share state need synchronization.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -