How can two sync Methods (same Object) in Java run at the same time?

I was searching for a wait() and notify() example in the internet and found the following example.
In the following Code-Block, both getValue() and setValue Methods are synchronized. If i create two Threads and the first Thread gets the lock, isn’t it true, that the second Thread will wait indefinitely, until the first Thread releases the Lock? So it is not possible, that getValue() and setValue() are run at the same time? If yes the wait() and notify() methods would be there for nothing.

tldr: How can getValue() and setValue() methods be called from different Threads at the same time?

public class Data {
    private int value;
    private boolean available = false;

    public synchronized int getValue() {
        while (!available) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        available = false;
        notifyAll();
        return value;
    }

    public synchronized void setValue(int value) {
        while (available) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        this.value = value;
        available = true;
        notifyAll();
    }
}

>Solution :

Quoting the documentation for Object.wait:

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object.

Essentially, wait is a special case that allows other threads to claim the lock until it is notified.

Leave a Reply