neo360
neo360

Reputation: 49

synchronised block and synchronised methods of the same instance

I am a bit confused about synchronized-blocks in Java.

If one thread enters a synchronized-block of an instance of a class, can other threads use synchronized-methods of the same instance of the same class?

void myMain() {
    synchronized(this) {
        while(suspendFlag)
             wait();
        }
    }
}

synchronized void mysuspend() {
    suspendFlag = true;
}

Upvotes: 1

Views: 81

Answers (2)

SirFartALot
SirFartALot

Reputation: 1225

Yes, because they are independently callable. A thread is not attached to a class or an instance of it. Each method of a class may be called independently from different threads.

What can limit this independence are synchronized methods. They are shortcuts for synchronized(this) {...} as method body.

Whenever a synchronized block is entered, the monitor on the associated instance is held.

A wait() frees the monitor on the surrounding synchronized block again, so other synchronized blocks can be executed.

There is a problem with your code: wait() will wait until a notify() on the monitor is called. But in your code neither a notify() is called, nor has the wait() a timeout.

Your while(suspendFlag) wait(); will then wait forever...

Upvotes: 0

shani klein
shani klein

Reputation: 344

synchronized void mysuspend(){
    suspendFlag = true;
}

is equivalent to

void mysuspend(){
    synchronized(this) {
        suspendFlag = true;
    }
}

So in your code it is not possible that one thread enters a synchronized block of an instance of a class and other threads use synchronized method mysuspend()

Upvotes: 1

Related Questions