The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: Threads: Doing Two or More Tasks at Once

Reacquiring a Lock

The same thread can call a synchronized method on an object for which it already holds the lock, thereby reacquiring the lock. The Java runtime environment allows a thread to reacquire a lock because the locks are reentrant. Reentrant locks are important because they eliminate the possibility of a single thread having to wait for a lock that it already holds.

Consider the following.

public class Reentrant {
    public synchronized void a() {
        b();
        System.out.format("Here I am, in a().%n");
    }
    public synchronized void b() {
        System.out.format("Here I am, in b().%n");
    }
}
Reentrant contains two synchronized methods: a and b. The first, a, calls the other, b. When control enters method a, the current thread acquires the lock for the Reentrant object. Now, a calls b; because b is also synchronized, the thread attempts to acquire the same lock again. Because the Java platform supports reentrant locks, this works. In platforms that don't support reentrant locks, this sequence of method calls causes a deadlock. The current thread can acquire the Reentrant object's lock again, and both a and b execute to conclusion, as is evidenced by the following output.
Here I am, in b().
Here I am, in a().

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.