I'm trying to illustrate the use and importance of volatile
with an example that would really not give a good result if volatile
was omitted.
But I'm not really used to using volatile
. The idea of the following code is to cause an infinite loop if volatile
is omitted, and be perfectly thread-safe if volatile
is present. Is the following code thread-safe? Do you have any other realistic and short example of code that uses volatile
and would give an obviously incorrect result without it?
Here's the code:
public class VolatileTest implements Runnable {
private int count;
private volatile boolean stopped;
@Override
public void run() {
while (!stopped) {
count++;
}
System.out.println("Count 1 = " + count);
}
public void stopCounting() {
stopped = true;
}
public int getCount() {
if (!stopped) {
throw new IllegalStateException("not stopped yet.");
}
return count;
}
public static void main(String[] args) throws InterruptedException {
VolatileTest vt = new VolatileTest();
Thread t = new Thread(vt);
t.start();
Thread.sleep(1000L);
vt.stopCounting();
System.out.println("Count 2 = " + vt.getCount());
}
}
See Question&Answers more detail:os