It has always been difficult for me to illustrate concurrency problems in a convincing way: well, well, this is all well and good going on, first and foremost, but why does one care? Is there a real problem? There are many, many poorly written, poorly synchronized programs โ and they still work most of the time.
I used to find a resort in โwork most of the time when VS worksโ rhetoric, but to be honest, this is a weak approach. So I needed an example that would make the difference obvious - and preferably painful.
So here is a version that actually shows the difference:
public class VolatileExample implements Runnable { public static boolean flag = true;
Simple show:
Waiting 1319229217263 stopping 1319229227263 Waiting 1319229242728 stopped 1319229242728 Delay: 15
That is, it takes more than ten seconds for the current thread (15 here) to notice that any changes have occurred.
With volatile
you have:
Waiting 1319229288280 stopping 1319229298281 stopped 1319229298281 Delay: 0
that is, to leave immediately (almost). The resolution of currentTimeMillis
is about 10 ms, so the difference is more than 1000 times.
Note that this was a version of Apple (ex-) Sun JDK, with the -server
option. A 10 second wait has been added to let the JIT compiler know that the loop is hot enough and optimize it.
Hope this helps.
source share