I want to implement the usual cooperative mechanism for canceling a thread. However the java memory model was only fixed in JDK5 while I’m in a pre-JDK5 environment. I understand, this means that doing something like this, as espoused in SCIP, will not be correct.
class Worker implements Runnable { private volatile boolean _canceled; public void cancel() { _canceled = true; } public void run() { while( ! _canceled ) { // do my Stuff } } }
I’m thinking of using an AtomicBoolean to encapsulate the _canceled variable. Any other alternatives ?
AtomicBooleanwas also added in JDK5, so this isn’t available unless you are using the backport. However, yes, the atomic class from the backport may be the best choice, as you know it was written by people who are versed in what works in each version of the JVM virtual machine spec.