borune
borune

Reputation: 568

java synchronized on object vs synchronized on this

i want to write own simple semaphore and done it as follows:

class Semaphore {
    private boolean done;
    private final Object lock = new Object();

    public Semaphore(boolean done){ this.done = done;}

    public void acquire() throws InterruptedException {
        synchronized (lock) {
            while (!done)
                lock.wait();

            done = false;
        }
    }

    public void release() {
        synchronized (lock) {
            done = true;
            lock.notify();
        }
    }
}

it works fine. But if i replace synchronized (lock) with synchronize (this) it begins to throw IllegalMonitorStateException. Why so?

Upvotes: 1

Views: 137

Answers (1)

Ravi
Ravi

Reputation: 31397

As @Alexei Kaigorodov mentioned in comment, when you replace synchronized (lock) with synchronize (this). Then, you need to also replace lock to this in your code.

As this indicate to current object which is different than lock object.

Now, you replaced synchronized (lock) with synchronize (this) which means now you are trying to acquire lock on current object but you were waiting on object of Object class.

This works absolutely fine :

public void acquire() throws InterruptedException {
    synchronized (this) {
        while (!done)
            this.wait();

        done = false;
    }
}

public void release() {
    synchronized (this) {
        done = true;
        this.notify();
    }
}

Upvotes: 2

Related Questions