Java Reference
In-Depth Information
30.31
✓
✓
What are the similarities and differences between a lock and a semaphore?
Check
30.32
Point
How do you create a semaphore that allows three concurrent threads? How do you
acquire a semaphore? How do you release a semaphore?
Deadlocks can be avoided by using a proper resource ordering.
Key
Point
Sometimes two or more threads need to acquire the locks on several shared objects. This could
cause a
deadlock
, in which each thread has the lock on one of the objects and is waiting for
the lock on the other object. Consider the scenario with two threads and two objects, as shown
in Figure 30.24. Thread 1 has acquired a lock on
object1
, and Thread 2 has acquired a lock
on
object2
. Now Thread 1 is waiting for the lock on
object2
, and Thread 2 for the lock on
object1
. Each thread waits for the other to release the lock it needs and until that happens,
neither can continue to run.
deadlock
Step
1
2
3
4
5
6
Thread 1
Thread 2
synchronized
(object1) {
synchronized
(object2) {
// do something here
// do something here
synchronized
(object2) {
synchronized
(object1) {
// do something here
// do something here
}
}
}
}
Wait for Thread 2 to
release the lock on
Wait for Thread 1 to
release the lock on
object2
object1
F
IGURE
30.24
Thread 1 and Thread 2 are deadlocked.
Deadlock is easily avoided by using a simple technique known as
resource ordering
. With
this technique, you assign an order to all the objects whose locks must be acquired and ensure
that each thread acquires the locks in that order. For the example in Figure 30.24, suppose
that the objects are ordered as
object1
and
object2
. Using the resource ordering technique,
Thread 2 must acquire a lock on
object1
first, then on
object2
. Once Thread 1 acquires a
lock on
object1
, Thread 2 has to wait for a lock on
object1
. Thus, Thread 1 will be able to
acquire a lock on
object2
and no deadlock will occur.
resource ordering
30.33
✓
✓
What is a deadlock? How can you avoid deadlock?
Check
Point
A thread state indicates the status of thread.
Key
Point
Tasks are executed in threads. Threads can be in one of five states: New, Ready, Running,
Blocked, or Finished (see Figure 30.25).
When a thread is newly created, it enters the
New
state
. After a thread is started by calling
its
start()
method, it enters the
Ready
state
. A ready thread is runnable but may not be run-
ning yet. The operating system has to allocate CPU time to it.
When a ready thread begins executing, it enters the
Running
state
. A running thread can
enter the
Ready
state if its given CPU time expires or its
yield()
method is called.
Search WWH ::
Custom Search