The basic concept

  • Early JDK versions of synchronized were heavyweight and required calls to the OS, making them time-consuming.
  • Jdk1.6 began to be optimized through the JVM, with synchronized upgrades.
  • Synchronized locks are not lock codes but lock objects, so do not use constants and primitive data types.

Lock Upgrade Concept

In essence, this is to reduce the time problems caused by each application to the operating system.

Flow (bloat)

  1. No lock (when the lock object is initialized
  2. After the lock is started, the thread ID, Markword, will be recorded for the first thread entered by the lock object, which belongs to biased lock.
  3. When another thread requests the lock object, it should directly enter the wait queue, but there is a possibility that the thread holding the lock is about to complete and release the lock, so if the thread’s execution code is short and the number of spinning threads is not large, it will upgrade to the spin lock.
  4. When the spin lock reaches the number of spins (default is 10) and still does not get the lock, it is upgraded to heavyweight lock.

supplement

  1. The memory of the operating system is divided into user memory and system memory. The system can access all of the memory, but users can only access user memory. Therefore, some operations need to be requested from the system, such as creating threads. The same goes for heavyweight locks, which change from user mode to kernel mode.