Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading