Java Reference
In-Depth Information
There's no need to synchronize methods that don't use state information in the class. If
your method doesn't use internal member variables, doesn't modify an external object,
and doesn't modify an object that was passed in as a parameter, don't synchronize it.
Don't oversynchronize. Make sure you know exactly why your method or data structure
is synchronized. If you can't articulate the need for synchronization to your own satis-
faction, you probably should reexamine the original need.
Immutable objects, such as String s and Integer s, never need synchronization. This
applies even to member variables, because immutable objects can't be modified.
However, a member variable referring to an immutable object may still need synchro-
nization if the member variable itself is mutable.
Don't multithread needlessly. Unless your threads are doing a lot of blocking, single
threading is often faster.
When working with Swing, feel free to create and insert components into any container
that hasn't been realized yet. To be realized, a component must be able to receive paint
or validation events—this means before show , setVisible(true) , or pack has been
called on the component.
Don't get confused by internally synchronized classes such as Vector . All an internally
synchronized class promises is to perform its actions atomically. This means that if one
thread code executes myVector.add("test") , and another thread slices in, if that new
thread executes myVector.contains("test") it will return true. This behavior is not
guaranteed with, say, an ArrayList . You will usually need to use synchronized methods
to interact with these variables.
Try to minimize actions performed within your synchronized blocks, since no other
thread will be able to obtain the lock your code is synchronized on for the duration,
thus reducing concurrency.
Avoid depending on thread priority as a mechanism of thread control. Different operat-
ing systems use distinct algorithms to deal with thread priority, and different JVMs use
different algorithms still. This could lead to your program acting wildly different from
one platform to the next. You best bet is to avoid the ambiguity of thread priorities,
especially where the SCJD exam is concerned.
Don't synchronize your thread's run method. Synchronizing your thread's run method
can lead to a lot of complications, and it's a bad idea.
If you are checking a condition in a synchronized block of code, use a while loop and
not an if statement. If your thread slices out in the middle of executing your if state-
ment, then the thread will resume exactly where it left off when it slices back in.
Counterintuitively, this is not a good thing, because the condition that was true when
your thread sliced out might no longer be true, because another thread could have
changed it.
Search WWH ::




Custom Search