|
Home
Synchronization and concurrency
wait/notify
final
volatile
synchronized keyword
Java threading
Deadlock (and avoiding it)
Java 5: ConcurrentHashMap
Atomic variables
Explicit locks
Queues
Semaphores
CountDownLatch
CyclicBarrier
Typical use of volatile in JavaWe mentioned on the previous page that a volatile variable is one whose value is always written to and read from "main memory". That means that different threads can access the variable.1. 1. Recall that without using volatile (or some other synchronization mechanism), then thread A doesn't know that thread B might access the variable. So thread A thinks it's fair game to just cache the value of the variable in a register or in its local memory, and we run into problems. A typical example of a simple variable that is written to and read from different threads is 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. If you don't like infinite loops, this is undesirable. Volatile, memory synchronization and Java 5We mentioned earlier that the meaning of volatile was tightened up in Java 5, and this tightened definition of volatile has actually been in part what has allowed some of the new concurrency facilities of Java 5. On the next page we'll look in more detail at the definition of volatile in Java 5.
Got a question about Java?
Ask on the Javamex forums!
Software
Copyright © Javamex UK 2012. All rights reserved. |