Java Reference
In-Depth Information
volatile
Java provides another keyword for dealing with concurrent access to data. This is
the volatile keyword, and it indicates that before being used by application code,
the value of the field or variable must be reread from main memory. Equally, after a
volatile value has been modified, then as soon as the write to the variable has com‐
pleted, it must be written back to main memory.
One common usage of the volatile keyword is in the “run-until-shutdown” pat‐
tern. This is used in multithreaded programming where an external user or system
needs to signal to a processing thread that it should finish the current job being
worked on and then shut down gracefully. This is sometimes called the “Graceful
Completion” pattern. Let's look at a typical example, supposing that this code for
our processing thread is in a class that implements Runnable :
private volatile boolean shutdown = false ;
public void shutdown () {
shutdown = true ;
}
public void run () {
while (! shutdown ) {
// ... process another task
}
}
All the time that the shutdown() method is not called by another thread, the pro‐
cessing thread continues to sequentially process tasks (this is often combined very
usefully with a BlockingQueue to deliver work). Once shutdown() is called by
another thread, then the processing thread immediately sees the shutdown flag
change to true . This does not affect the running job, but once the task finishes, the
processing thread will not accept another task and instead will shut down gracefully.
y
y d
Useful Methods of Thread
When creating new application threads, the Thread class has a number of methods
on it to make the programmer's life easier. This is not an exhaustive list—there are
many other methods on Thread , but this is a description of some of the more com‐
mon methods.
getId()
This method returns the ID number of the thread, as a long . This ID will stay the
same for the lifetime of the thread.
getPriority() and setPriority()
These methods are used to control the priority of threads. The scheduler decides
how to handle thread priorities—for example, one strategy could be to not have any
Search WWH ::




Custom Search