I have a question which may sound very basic but here it is. As commonly known in Java the synchronize
keyword is used to deal with multiples threads accessing one particular instance. Now imagine if an instance A has a synchronized method do()
. Does that mean that if a thread T1 executes the method do()
and therefore acquires the lock of A, no other thread will access the instance A until T1 releases the lock (even if other methods are not synchronized)? or it means that all not-synchronized methods (or blocks of code) are accessible except that particular do()
method which maybe executed by only one thread at a time?
-
I don't see any good answers here. The older question that somebody linked to has a good answer to _why_ and _when_ to use `synchronized`, but no concise answer to what it actually does. The answer is simple: The JVM will not allow two threads to `synchronize` on the same object at the same time. That's all there is to it. Remember that a synchronized instance method synchronizes on `this`, and a synchronized static method synchronizes on the class object, and that's all you need to know about what `synchronized` actually _does_. – Solomon Slow Sep 08 '14 at 13:34
3 Answers
Straight from the Java documentation:
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.
Therefore, your latter explanation is correct.

- 105,112
- 20
- 162
- 194
A synchronized method ensures that this method is not called for more than one object instances simultaneously and also during execution of a synchronized method all the associated instance variables are refreshed before starting executing the method.

- 6,980
- 4
- 30
- 69
If T1 gets a lock on method do()
i.e method is under synchronized block.
and other portion of program say method display()
is not synchronized then other threads can access this method.
So your or is correct.

- 9,728
- 7
- 66
- 71