The basic principle of synchronized

Synchronized is a way to achieve mutual exclusion synchronization implemented by JVM. If you look at the compiled bytecode of the program block modified by synchronized, you will find that the program block modified by Synchronized is compiled before and after compilation. The device generates two bytecode instructions, monitorenter and monitorexit.
这两个字节码什么意思呢?
When the virtual machine executes the monitorenter instruction, it must first try to acquire the lock of the object. If the object is not locked, or the current thread already owns the lock of the object, the lock counter is +1, and the lock count is -1 when the monitorexit instruction is executed. When the counter is 0, the lock is released. If the acquisition of the object fails, the current thread will block and wait until the object lock is released by another thread. Synchronized in Java sets the mark through the object header to achieve the acquisition of the lock and The purpose of releasing the lock.

There will be two mointorexit in the decompiled bytecode file. The second mointorexit is to prevent the program from exiting due to an exception, and the lock is not released in time to ensure the normal release of the lock

Guess you like

Origin blog.csdn.net/qq_43518425/article/details/114725877