Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Synchronization works in Java?

I have a doubt regarding Java Synchronization . I want to know if I have three Synchronized methods in my class and a thread acquires lock in one synchronized method other two will be locked ? I am asking this question because I am confused with the following statement .

While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread

like image 812
Raj Avatar asked Jun 25 '12 06:06

Raj


2 Answers

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.

like image 129
bezmax Avatar answered Nov 25 '22 11:11

bezmax


Yes.
To execute synchronized method thread need to obtain lock on object and only one thread at a time can obtain lock on object.

like image 21
Ajinkya Avatar answered Nov 25 '22 11:11

Ajinkya