Synchronized is one of the Java keywords that provides an atomic internal lock that every object in Java can use as a synchronization lock. This lock, invisible to the Java built-in user, is an internal, or monitor lock.

[TOC]

Synchronized memory semantics

Entering a synchronized block is when the current thread clears the variables used in the synchronized block from its working memory and loads them from main memory.

Exiting a synchronized block is when the current thread flushs changes made to variables used in a synchronized block to main memory.

Monitor

Introduction to the

The monitor in the monitor lock mentioned above is also translated as a pipe procedure. Semaphore (semaphore) and Mutex (mutex) are two important synchronization primitives that are often used when faced with multi-threaded operations in operating systems, but manipulating them directly can be very complicated. In order to make it easier to write correct programs, monitor is proposed on the basis of both.

Note that the operating system does not support Monitor. Monitor is supported by programming languages. For example, C does not support Monitor, but Java does. Monitor is implemented differently for different languages.

In the history of Monitor, there are three different models:

  • Hasen model
  • Hoare model
  • MESA model

Later mentionedmonitorAre implemented in Javamonitor

Java is implemented by referring to MESA model. In the HostSpot simulator used by JVM, monitor is implemented by C++ and its main data structure is as follows:

ObjectMonitor() {
    _header       = NULL;
    _count        = 0; / / monitor into the number
    _waiters      = 0,
    _recursions   = 0;  // The number of threads reentrant
    _object       = NULL;
    _owner        = NULL; // Identifies the thread that owns the monitor
    _WaitSet      = NULL; _WaitSet is the first node in the list
    _WaitSetLock  = 0 ;
    _Responsible  = NULL ;
    _succ         = NULL ;
    _cxq          = NULL ; // Multi-threaded contention lock entry when the single necklace table
    FreeNext      = NULL ;
    _EntryList    = NULL ; // Threads in the waiting block state are added to the list
    _SpinFreq     = 0 ;
    _SpinClock    = 0 ;
    OwnerIsThread = 0 ;
  }
Copy the code

Using the synchronized keyword, you usually need to specify an object, called a Monitor Object. HotSpot automatically creates a Monitor object associated with that object.

The characteristics of

Monitor allows only one process/thread to enter a critical section defined by Monitor at a time (mutually exclusive). At the same time, processes/threads that fail to enter critical sections need to be managed, such as blocking and waking up. Monitor, as a synchronization tool, provides a mechanism for managing process/thread state.

Semaphore (semaphore) and Mutex (mutex) require the user to implement the above mechanism, while Monitor implements it internally and provides a simpler and easier interface externally.

When a thread needs to acquire a lock, it puts an Entry Set and waits.

If the thread has a lock, it is called the Owner of the current lock.

If the thread running the lock finds that it needs to wait for an external condition, it can call the wait method and enter the wait Set.

A thread that enters the Wait Set will be awakened by a call to notify and try again to acquire the lock and become the Owner.

Also need to pay attention to point, thread in and out of the critical zone, will implement moniterenter/moniterexist system call respectively, at the same time the Java thread is actually a mapping of the operating system thread. Therefore, before Java SE1.6, synchronized would cause thread state switching (user state and kernel state) and increase the running cost. Synchronized was optimized after Java SE1.6 to introduce biased and lightweight locking.

Lock markers in the object memory model

Here, we need to understand the memory model of Java objects. Java objects consist of three parts:

  • Object header: contains Mark Word, Class Pointer
  • The instance data
  • Alignment filling

The MarkWord of the object header has a total of 32 bits, which contains the status information of the lock. It can be seen that the MarkWord contains four lock states:

  • unlocked
  • Biased locking
  • Lightweight lock
  • Heavyweight lock

The lock will correspond to the above four states according to the different competition conditions, upgrade from top to bottom, and cannot be degraded.

Lock the upgrade process can refer to: www.bilibili.com/video/BV1xT…

Refer to the link

Blog.csdn.net/TZ845195485…

Blog.csdn.net/qq_36934826…

www.cnblogs.com/wade-luffy/…