Java Reference
In-Depth Information
Condition wait errors. When waiting on a condition queue, Object.wait or Condi-
tion. await should be called in a loop, with the appropriate lock held, after
testing some state predicate (see Chapter 14 ). Calling Object.wait or Condi-
tion.await without the lock held, not in a loop, or without testing some state pre-
dicate is almost certainly an error.
Misuse of Lock and Condition . Using a Lock as the lock argument for a syn-
chronized block is likely to be a typo, as is calling Condition.wait instead of
await (though the latter would likely be caught in testing, since it would throw an
IllegalMonitorStateException the first time it was called).
Sleeping or waiting while holding a lock. Calling Thread.sleep with a lock held can
prevent other threads from making progress for a long time and is therefore a poten-
tially serious liveness hazard. Calling Object.wait or Condition.await with
two locks held poses a similar hazard.
Spin loops. Code that does nothing but spin (busy wait) checking a field for an expected
value can waste CPU time and, if the field is not volatile, is not guaranteed to termin-
ate. Latches or condition waits are often a better technique when waiting for a state
transition to occur.
12.4.3. Aspect-oriented Testing Techniques
As of this writing, aspect-oriented programming (AOP) techniques have only limited applic-
ability to concurrency, because most popular AOP tools do not yet support pointcuts at syn-
chronization points. However, AOP can be applied to assert invariants or some aspects of
compliance with synchronization policies. For example, ( Laddad, 2003 ) provides an example
of using an aspect to wrap all calls to non-thread-safe Swing methods with the assertion that
the call is occurring in the event thread. As it requires no code changes, this technique is easy
to apply and can disclose subtle publication and thread-confinement errors.
12.4.4. Profilers and Monitoring Tools
Most commercial profiling tools have some support for threads. They vary in feature set and
effectiveness, but can often provide insight into what your program is doing (although pro-
filing tools are usually intrusive and can substantially affect program timing and behavior).
Most offer a display showing a timeline for each thread with different colors for the various
thread states (runnable, blocked waiting for a lock, blocked waiting for I/O, etc.). Such a dis-
play can show how effectively your program is utilizing the available CPU resources, and if
it is doing badly, where to look for the cause. (Many profilers also claim features for identi-
Search WWH ::




Custom Search