java - Multithreading "unpredictable" behavior -
this question has answer here:
i going through use cases volatile , have encountered below scenario:
private static boolean stop = false; public static void main(string[] args) throws interruptedexception { thread runner = new thread(new runnable() { @override public void run() { int = 0; long start = system.currenttimemillis(); while(!stop){ i++; } system.out.println("i m done after "+(system.currenttimemillis() - start)); } }); runner.start(); thread.sleep(2000); stop = true; }
the above code runs indefinitely. fine due hoisting done compiler in attempt optimize code. however, if replace, i++ other statement e.g. system.out.println("hello"). stops after 2 seconds.
why behavior this? using jdk1.7.0_51.
note: know should declare stop volatile. however, know reason behavior in above case.
the standard output shared resource across threads. java's printstream
class made thread-safe using synchronized blocks, , synchronized blocks memory barriers in java, that's why changes on stop
field become visible inside loop. however, shouldn't rely on this.
for example, take @ printstream.println
implementation:
public void println(string paramstring) { synchronized (this) { print(paramstring); newline(); } }
Comments
Post a Comment