Pavel Lyakhov
Pavel Lyakhov

Reputation: 23

Waiting for semaphore inside synchronized method

We have something like that:

public class TaskExecutor extends Thread {    
    private static Semaphore globalStackLocker;

    private synchronized Object popFromGlobalStack() {
        //do something
        try {
            globalStackLocker.acquire();
        } catch (InterruptedException e) {}
    }
    //somwhere here are methods that allow to release semaphore
}

The idea is that I have synchronized method and I check my semaphore inside. If this semaphore is locked, this thread will be waiting for it to unlock.

The question is - while he is waiting, will the synchronized method be unlocked for other threads?

It looks like "yes" to me - one thread is still waiting, so another can try and execute this method. I, actually, found a few answers that seem proving this, but I want to be sure.


Ok, I see. What if I use .wait() instead of semaphore? It shares the same problem?

public class MyClass() extends Thread {
    private static Object lock;
    private synchronized void myPop() { 
        //do something with shared memory (that's why I need synchronize) 
        try { lock.wait() } catch (InterruptedException e) {} 
    } 
}

Can there be multiple threads waiting inside one synchronized method? Or maybe I should just use synchronized blocks instead in my method? (in "do something" part)

Upvotes: 2

Views: 1356

Answers (1)

Jean Logeart
Jean Logeart

Reputation: 53809

No it won't: other Threads will block on the same TaskExecutor instance because of the synchronized.

Since you have a static Semaphore, synchronized is unnecessary since your semaphore ensure a stronger constraint: threads are blocking not only on the same TaskExecutor but globally (as long as the semaphore is acquired/released equivalently to the synchronized)

Upvotes: 3

Related Questions