In order to properly understand the issues and solutions for concurrency in Java, I was going through the official Java tutorial. In one of the pages they defined Intrin
would I be unable to call another synchronized method of the same class? If yes, then the whole purpose of having synchronized methods is defeated. Isn't it?
No. You can't call other synchronized
method on same object for Object level lock and you can't call other static sysnchronized
method on same class.
But it does not defeat the purpose of having synchronisation.
If you follow the other documentation page on synchronized methods:
Making these methods
synchronized
has two effects:
- First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
- Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
If you allow two synchronized
method to run in parallel. you will bound to get memory inconsistency errors on shared data.
On a different note, Lock provides better alternative synchronized
construct.
Related SE question:
Synchronization vs Lock