sychronized

Synchronize method blocks:
Each object has a monitor lock (monitor).
When the thread executes the monitorenter instruction, it tries to acquire ownership of the monitor. The process is as follows:
1. If the monitor's entry count is 0, the thread enters the monitor and sets the entry count to 1. The thread is the owner of the monitor.
2. If the thread already owns the monitor and just re-enters it, the monitor entry number is incremented by 1.
3. If other threads have already occupied the monitor, the thread enters the blocking state until the monitor's entry count is 0, and then tries to obtain the ownership of the monitor.
The thread executes the monitorexit instruction to exit the monitor. The process is as follows:
1. The thread executing the monitorexit instruction must be the owner of the monitor.
2. The thread executes the instruction, and the monitor's entry count is decremented. When the monitor's entry count is 0, the thread exits the monitor and is no longer the owner of the monitor. Other threads blocked by the monitor can try to acquire the ownership of the monitor.
Note: methods such as wait/notify also depend on the monitor object, so methods such as wait/notify can only be called in synchronized blocks or methods, otherwise an exception of java.lang.IllegalMonitorStateException will be thrown
   
Synchronize the method:
The synchronization of the method is not completed by the instructions monitorenter and monitorexit (theoretically, it can also be achieved by these two instructions), but compared with the ordinary method, the ACC_SYNCHRONIZED identifier is added to the constant pool.
The JVM implements method synchronization based on this identifier: when the method is called, the calling instruction will check whether the ACC_SYNCHRONIZED access flag of the method is set. If it is set, the execution thread will first obtain the monitor, and then execute the method body after the acquisition is successful. , the monitor is released after the method is executed. During the execution of the method, no other thread can obtain the same monitor object again. In fact, there is no difference in essence, except that the synchronization of the method is implemented in an implicit way, without the need for bytecode.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325941720&siteId=291194637