Understand the meaning of synchronized

Understand the meaning
of synchronized 1. Synchronized is to add a mutual exclusion lock mechanism to the current NumOps type object: There can only be one lock.
2. When a thread is executing in a synchronized method, other threads cannot enter the object. In any synchronous method, you can enter the non-synchronous method

Common 4 types of Java thread locks: atomic weight AtomicInteger, semaphore Semaphone, synchronized processing synchronized and reentrant lock ReentrantLock

Before jdk6 was a heavyweight lock, JDK6 started to be optimized for a total of four lock states, lock-free state (no synchronized), biased lock, lightweight lock and heavyweight lock. The change of the lock state is carried out according to the degree of competition. Under conditions of almost no competition, biased locks will be used. Under conditions of light competition, they will be upgraded from biased locks to lightweight locks. Under severe competition conditions , Will be upgraded to a heavyweight lock. With the competition of locks, locks can be upgraded from biased locks to lightweight locks, and then upgraded heavyweight locks, but the upgrade of locks is one-way, which means that it can only be upgraded from low to high, and there will be no locks. Downgrade

When using synchronized locking bytecode, there will be two instructions, monitorenter and monitorexit, which can be understood as locking before the code block is executed, and unlocking when exiting synchronization

Guess you like

Origin blog.csdn.net/qq_45874107/article/details/113805978