Hello World
Hello World

Reputation: 983

In Java about Synchronization and monitor in Thread

I read that a thread that owns a monitor can reenter the same monitor if it need to do so, how that can be achieved. Any help will be greatly appreciated.

Upvotes: 2

Views: 111

Answers (1)

Warren Dew
Warren Dew

Reputation: 8928

The following function takes ownership of a monitor:

function_a() {
    synchronized(monitor) {
        function_b();
    }
}

Now let's say function_b looks like this:

function_b() {
    synchronized(monitor) {
        do_something();
    }
}

In function_b, our thread "reenters" the monitor by declaring a second synchronization on it. Since the thread already owns the monitor, the thread can continue into the second synchronized block.

Upvotes: 4

Related Questions