At work today, I came across the volatile
keyword in Java. Not being very familiar with it, I found this explanation.
Given the detail in which that arti
volatile
is very useful to stop threads.
Not that you should be writing your own threads, Java 1.6 has a lot of nice thread pools. But if you are sure you need a thread, you'll need to know how to stop it.
The pattern I use for threads is:
public class Foo extends Thread {
private volatile boolean close = false;
public void run() {
while(!close) {
// do work
}
}
public void close() {
close = true;
// interrupt here if needed
}
}
In the above code segment, the thread reading close
in the while loop is different from the one that calls close()
. Without volatile, the thread running the loop may never see the change to close.
Notice how there's no need for synchronization