Question

I was reading about JAVA synchronization.

I have 2 methods in my class.

public synchronized void eat()
{
    System.out.println("eat");
    eatDinner();
}

public synchronized void eatDinner()
{
    System.out.println("eat");
}

Both of my methods are synchronized.

Now Is it possible for 2 threads one is calling eat() and another eatDinner() to run simultaneously? And If thread2 has not still executing eatDinner() . Can thread1 can call eatDinner() from eat()?

Was it helpful?

Solution

No, it is not possible for two threads to run the methods eat and eatDinner simultaneously. (Caveat: as long as these methods are invoked on the same instance of the class)

The synchronized keywords, when applied to a non-static method, synchronizes on the object itself.

Your code can be rewritten, without changing the meaning, as:

public void eat() {
    synchronized (this) {
        System.out.println("eat");
        eatDinner();
    }
}

public void eatDinner() {
    synchronized (this) {
        System.out.println("eat");
    }
}

This probably makes it easier to see that they are both synchronizing on the same monitor. Each java object has a monitor.

As long as 'thread1' is holding the monitor of your object, it can enter other synchronized blocks on the same monitor. 'thread1' has to exit all synchronized blocks (exist the blocks as many times as it has entered them) before another thread can take ownership of the monitor.

So thread1 can call eatDinner if it is already in the eat method - no problem. But if thread2 is currently in the eat method, then thread1 will block when it calls eatDinner until thread2 has finished both eatDinner and eat.

Addition: In response to your comment

@Raj: If two threads are created by same class instances, then?

It is not important how the threads were created - it doesn't matter if that happened from within the same class or from completely different locations in your code. Two different threads are always independent.

It only matters on which object's monitor you synchronize: each object instance has one 'monitor'. You can't see this monitor - it doesn't have a name, but it's there and it is used by the synchronized keywords and by the wait, notify and notifyAll methods defined in java.lang.Object.

OTHER TIPS

"Now Is it possible for 2 threads one is calling eat() and another eatDinner() to run simultaneously? "

on the same instance, no. they will block and only one will execute at once. different class instances, yes, they will not block eath other.

"Can thread1 can call eatDinner() from eat()"

yes. the lock is reentrant.

If 2 threads call methods on different class instances they can run methods simultaneously

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top