java - Are while true loops that check only for one condition thread safe? -


this question has answer here:

i'm using while loop checking condition become true:

while(game.gamestate != game.closing) {     if(reconnecting)     {         time = system.currenttimemillis();     }     else     {         while(time + desiredwait > system.currenttimemillis())         {             try{thread.sleep(5);}catch(interruptedexception e){}         }          time += desiredwait;     }      synchronized (game.gamestatelock)//added circumvent problem     {         if(game.gamestate == game.inprogress)//problematic condition         {             while(true)             {                 synchronized (lockstep.nextturns)                 {                     if(!lockstep.nextturns.isempty() || lockstep.currentturn == 0)                         break;                 }                  try{thread.sleep(5);}catch(interruptedexception e){}                  time = system.currenttimemillis();             }              lockstep.attemptturn();         }     } } 

the loop runs uninterrupted without sleeping (if reconnecting true), , therefore accesses game.gamestate (of type int) 2 times in each cycle. if gamestate changed in second thread (e.g. via network), while loop/if condition doesn't detect , continues refusing execute code in if block if should. added synchronized(game.gamestatelock) solves problem. hard debug, cause printing gamestate or else cause problem nonexistent. guess i/o interrupts/sleeps thread or causes write/read data, cache of cpu cleared , gamestate variable has been read cache whole time has reloaded ram.

can reason? assumed primitive data types not of problem when dealing multiple threads (unless you're checking boolean , setting block other threads). primitive data types in java thread safe? (i can't synchronize on them, needed dummy object)

"thread safe" not term looking for, may why struggling. code technically "thread safe", in won't encounter corruption due multi-threading. missing however, guarantees related "visibility". in situation, there no guarantee change made 1 thread "visible" another. there variety of ways make changes visible. in situation, making gamestate volatile sufficient force cross-thread visibility of changes value.


Comments