Each object has a lock (monitor, monitor Lock), the class object also has the lock, if the Synchronized keyword decorates the synchronization code block, through the anti-compilation can see, actually has a monitorenter and monitorexit instruction, namely, A thread must first obtain the monitor lock on the object in order to enter the synchronization code block, and if the other thread also acquires a lock on the object, it will block until the current thread releases the monitor lock. Synchronized (this) is the lock of the current object, and synchronized (A.class) is the lock class object.
If the Synchronized keyword modifies the normal method, the thread must first obtain the object's lock before calling the object's synchronization method, which is blocked if other threads are also calling other synchronization methods of the object. If the Synchronized keyword modifies the static method, because the static method belongs to the class, you must first obtain a lock on the class object.
By anti-compilation You can see that the Synchronized keyword is added before the method, essentially adding a
Acc_synchronized (Access SYNCHRONIZED) flag, when the method is called, first checks whether the method's acc_synchronized is set, and if set, the execution thread will first get the object's monitor lock, The method body can be executed after the method has been successfully executed before releasing monitor. No other thread can get the monitor lock on the object during the execution of the method.
The Synchronized keyword resolves atomicity (non-disruptive, mutex), visibility (guaranteed to be modified even if visible), and consistency issues (preventing reordering).
The underlying implementation of the Java synchronized keyword