Threads of Control |
The Java runtime system allows a thread to re-acquire a monitor that it already holds because Java monitors are re-entrant. Re-entrant monitors are important because they eliminate the possibility of a single thread deadlocking itself on a monitor that it already holds.Consider this class:
Reentrantcontains two synchronized methods:class Reentrant { public synchronized void a() { b(); System.out.println("here I am, in a()"); } public synchronized void b() { System.out.println("here I am, in b()"); } }a()
andb()
. The first synchronized method,a()
, calls the other synchronized method,b()
.When control enters method
a()
, the current thread acquires the monitor for the Reentrant object. Now,a()
callsb()
and becauseb()
is also synchronized the thread attempts to acquire the same monitor again. Because Java supports re-entrant monitors, this works. The current thread can acquire the Reentrant object's monitor again and botha()
andb()
execute to conclusion as is evidenced by the output:In systems that don't support re-entrant monitors, this sequence of method calls would cause deadlock.here I am, in b() here I am, in a()
Threads of Control |