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
Synchronization in java is done through aquiering the monitor on some specific Object. Therefore, if you do this:
Then those two blocks will be protected by execution of 2 different threads at any time while
someVariableis not modified. Basically, it’s said that those two blocks are synchronized against the variablesomeVariable.When you put
synchronizedon the method, it basically means the same assynchronized (this), that is, a synchronization on the object this method is executed on.That is:
Means the same as:
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
thisobject.