Friday, January 16, 2009

volatile keyword

Lock free, an alternative to synchronization and lock. A volatile variable is one whose value is always written to and read from "main memory" and not cached by register or thread. That means that different threads can access the variable.

A typical example of a "stop request" flag allowing one thread to signal to another to finish:


public class StoppableTask extends Thread {
private volatile boolean pleaseStop;
public void run() {
while (!pleaseStop) {
// do some stuff...
}

public void tellMeToStop() {
pleaseStop = true;
}
}

If the variable were not declared volatile (and without other synchronization), then it would be legal for the thread running the loop to cache the value of the variable at the start of the loop and never read it again.

See: The volatile keyword in Java 5

No comments: