Java Reference
In-Depth Information
While loops, on the other hand, are re-checked before your thread exits the block. Thus,
relevant state changes will be detected. The following snippet shows an example of this
technique:
synchronized (lockedRecords) {
while (lockedRecords.contains(upc)) {
lockedRecords.wait();
}
//do stuff
lockedRecords.notifyAll();
}
Use notifyAll instead of notify . notify only wakes a single waiting thread, while
notifyAll wakes all waiting threads.
Summary
In this chapter, we discussed some of the possibilities available to you when using threads,
and we pointed out some trouble spots to avoid. We discussed safe threading issues, threads
and Swing, blocking, waiting, and a host of other topics.
The best way to understand threading is to design your threading scheme, make predic-
tions about how it will function, and then test those predictions with the handy method in the
Thread class, holdsLock(Object) . Thread 's getState() and getStackTrace() methods can be
very handy for checking what another thread is doing. If your threads aren't behaving the way
you expected them to, explicitly record your assumptions (we suggest writing them down) and
then examine them one by one. Threading is a lot like grammar: There are a lot of rules, but
eventually you develop a sense for what works and what doesn't. (Or so I'm told.)
As you read the next chapters, please don't hesitate to refer back to this chapter when
needed.
FAQ Q What happens when a synchronized block/method calls an unsynchronized one?
A The unsynchronized block/method is treated as if it was synchronized.
Q What happens when a synchronized block/method calls a synchronized one within
the same object?
A If both methods are synchronizing on the same object, then nothing unusual happens
as far as you're concerned—there's no double synchronization or risk of deadlock. The
thread acquires an extra lock on the object, which in turn dissipates when the lock is
released.
Q Does locking an object lock all of its internal variables?
A No, absolutely not. Doing so would place a tremendous burden on the JVM, because it
would lock all their internal objects, and then the internal object of member variables
in turn, and so on. Java assumes that you understand this, and that you are only lock-
ing what you mean to lock.
Search WWH ::




Custom Search