Information Technology Reference
In-Depth Information
In general, sleep() is only appropriate when there is a particular real-
time moment when you want to perform some action. If you catch yourself
writing while(testOnObjectState() f sleep(); g, treat this is a big red
flag that you are probably making a mistake.
Similarly, if a thread needs to wait for an object's state to change, it should
wait on a condition variable, not just call yield() . Instead, yield() is
appropriate when a low priority thread that could make progress instead
yields the processor to let higher-priority threads run.
Two pitfalls in Java
Java is a modern type-safe language that included support for threads from its in-
ception. This built-in support makes multi-threaded programming in Java convenient.
However, some aspects of the language are too flexible and can encourage bad prac-
tices. We highlight two pitfalls here.
1. Avoid defining a synchronized block in the middle of a method
Java provides built in language support for shared objects (“monitors.”) The
base Object class, from which all classes inherit, includes a lock and a condition
variable as members. Then, any method declaration can include the keyword
synchronized to indicate that the object's lock is to be automatically acquired on
entry to the method and automatically released on any return from the method.
E.g.,
publicsynchronizedfoo(){
//Dosomething;lockisautomaticallyacquired/released.
}
This syntax is useful—it follows rule #2 above, and it frees the programmer from
having to worry about details like making sure the lock is released before every
possible return point including exceptions. The pitfall is that Java also allows a
synchronized block in the middle of a method. E.g.,
publicbar(){
//Dosomethingwithoutholdingthelock
synchronized{
//Dosomethingwhileholdingthelock
}
//Dosomethingwithoutholdingthelock
}
This construct violates rule #2 from Section 5.6.7 and suffers from the disadvan-
tages listed there. The solution is the same as discussed above: when you find
yourself tempted to write a synchronized block in the middle of a Java method,
treat that as a strong hint that you should define a separate method to more
clearly encapsulate the logical chunk you have identified.
2. Keep shared state classes separate from thread classses
Java defines a class called Thread that implements an interface called Runnable
that other classes can implement in order to be treated as threads by the runtime
system. To write the code that represents a thread's “main loop”, you typically
extend the Thread class or implement a class that implements Runnable.
 
Search WWH ::




Custom Search