The synchronized provides sequential access to a block of code (which can be an entire method) that it enters. Serializing access is performed using the object as a lock mutex .
The three main uses of synchronized :
a. By the static method:
static synchronized void someStaticMethod() {
B. According to the instance method:
synchronized void someInstanceMethod() { // The instance - ie "this" - is lock object for this block of code, which is the whole method }
C. On an arbitrary block of code:
private Object lock = new Object(); void someMethod() { synchronized (lock) {
In all cases, only one thread at a time can enter the synchronized block.
In all cases, if the same blocking object is used for several blocks, only one thread can enter any of the synchronized blocks. For example, if there are two other simultaneous threads that call methods, they will be blocked until the first thread exits this method.
source share