Learning others summary record, relatively shallow, there may be problems, welcome to correct.
Use 1.
- Modify normal methods (object locks)
- Modify static methods (class locks)
- Synchronized object lock Synchronzied (demo.class) class lock
2. Implementation principle
Monitorenter and MonitoreXit are reentrant, incrementing once monitor is executed and decrement once Monitorexit is executed, releasing the lock when it becomes 0.
3. The lock type
Synchronized heavyweight lock. Lock competition blocks threads and causes switching between user and kernel states, which affects performance. So biased locking and lightweight locking were introduced in jdk1.6. Synchronized There are four types of locks: none, biased, lightweight, and heavyweight
Biased locking
When a thread obtains the lock for the first time, it will run threadId several times in the Mark Word in the object header. When the thread executes again, it will determine whether the threadId in the object header is consistent. If the threadId is consistent, it is the same object lock, and then directly execute the code. If they are inconsistent, CAS will replace them. If they succeed, biased locks will be obtained. If they fail, biased locks will be upgraded to threads. Biased locks will not be released actively and will stop the world when revoked. Biased locking is enabled by default. You can configure the JVM parameter useBiasedLocking to control whether biased locking is enabled.
Lightweight locks (spinlocks)
When a thread acquires a biased lock, another thread will spin and wait. After spinning a certain number of times, it will upgrade to a heavyweight lock. Spin-locks are possible because locks are not competitive and can be acquired quickly.
Heavyweight lock
Currently the thread that acquired the lock executes, the other thread suspends, and when the lock is released, the lock is contested again.