Java Reference
In-Depth Information
(the method doesn't make the invoking thread wait). If another thread holds the lock,
the method returns
false
but continues executing. It is better to use the
synchron-
ized
keyword for synchronization and use
ReentrantLock
only when its features
are needed. For more information on the other methods provided by
Tip
While this is only a recipe book and proper threading techniques span their own
volumes, it is important to raise awareness of deadlocks.
Deadlocks
occur when two
locks are involved (and are acquired in reverse order within another thread). The
simplest way to avoid a deadlock is to avoid letting the lock “escape.” This means that
the lock, when acquired, should not execute code calling on other methods that could
possibly acquire a different lock. If that's not possible, release the lock before calling
such a method.
Care should be taken in that any operation that refers to one or both collections
needs to be protected by the same lock. Operations that depend on the result of one col-
lection to query the second collection need to be executed atomically; they need to be
done as a unit in which neither collection can change until the operation is completed.
10-6.
Splitting
Work
into
Separate
Threads
Problem
You have work that can be split into separate threads and want to maximize the use of
available CPU resources.
Solution
Use a
ThreadpoolExecutor
instance, which allows us to break the tasks into dis-
crete units. In the following example, a
BlockingQueue
is created, which includes a
Runnable
object. It then is passed to the
ThreadPoolExecutor
instance. The
ThreadPoolExecutor
is then initialized and started by calling the
pre-