How Synchronization works in Java?

Synchronization in java is done through aquiering the monitor on some specific Object. Therefore, if you do this:

class TestClass {
    SomeClass someVariable;

    public void myMethod () {
        synchronized (someVariable) {
            ...
        }
    }

    public void myOtherMethod() {
        synchronized (someVariable) {
            ...
        }
    }
}

Then those two blocks will be protected by execution of 2 different threads at any time while someVariable is not modified. Basically, it’s said that those two blocks are synchronized against the variable someVariable.

When you put synchronized on the method, it basically means the same as synchronized (this), that is, a synchronization on the object this method is executed on.

That is:

public synchronized void myMethod() {
    ...
}

Means the same as:

public void myMethod() {
    synchronized (this) {
       ...
    }
}

Therefore, to answer your question – yes, threads won’t be able to simultaneously call those methods in different threads, as they are both holding a reference to the same monitor, the monitor of this object.

Leave a Comment