java - Loop is not working unless I put a System.out.println() in it -


this question has answer here:

in graphic class have when press "m" make boolean m true, , have piece of code.

graphic.m = false; while(graphic.m == false){ } graphic.m = false; 

it won't work, not continue code ahead of it.

but if this

graphic.m = false; while(graphic.m == false){ system.out.println("m"); } graphic.m = false; 

it works prefectly, can explain why , how past this?

for ever work, other thread must setting graphic.m true. i'll assume that's happening.

my guess graphic.m not volatile field. means there's no formal happens-before relationship between 1 thread writing (setting true other thread) , thread reading (the code have). jvm free cache values within thread (or let cpu cores cache them, etc), , seems doing so.

system.out.println synchronized method, though. though doesn't have formal affect on graphic.m according jls, it's possible act of releasing/acquiring synchronization lock flush memory across cores such thread happens see graphic.m's latest value. emphasize: doesn't have happen java spec, , shouldn't rely on behavior -- if do, you're bitten hard-to-catch bug in future version of jvm, or different hardware, etc.

the solution make graphic.m volatile field (or get/set via synchronized method, or use atomicboolean).


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -