The principle of

Synchronized is an atomic built-in lock provided by Java. These built-in and unseen locks are also known as monitor locks. Monitorenter and Monitorexit bytecode instructions are appended to synchronized blocks of code after compilation, which rely on the operating system’s underlying mutex implementation. Its main role is to implement atomic operations and solve memory visibility problems for shared variables. An exclusive lock. When a thread acquires the lock, other threads must wait for the thread to release the lock before they can acquire the lock. Moreover, since Java threads and operating system native threads are one by one, threads will switch from user mode to kernel mode when they block or wake up. In memory, the locking process clears the shared variables in working memory and reads them from main memory, while the locking process writes the shared variables in working memory back to main memory.

Implementation process

When Monitorenter executes, it attempts to acquire the object lock. If the object is not locked or has acquired the lock, the lock counter +1 is used to queue other threads competing for the lock. Monitorexit executes the counter -1 and releases the lock when it equals 0. Threads in the wait queue continue to compete for locks.

Source code flow principle

  1. When multiple threads enter a synchronized code block, the entryList is entered first
  2. When a thread acquires the monitor lock, it assigns a value to the current thread and the counter +1
  3. If a thread calls wait, the lock is released, the current thread is set to NULL, the counter is -1, and the thread enters waitSet to be awakened. After calling notify or notifyAll, the thread enters entryList to compete for the lock
  4. If the thread completes, the lock is also released, counter -1, and the current thread is set to NULL

Overall principle flow