Thread synchronization and Object locks inside JVM

Source: Internet
Author: User

Thread synchronization

One of the advantages of the Java language is that he supports multithreading at the language level. These support focuses on synchronization (synchronization): Collaboration activities and data access between multiple threads. The mechanism used by Java to support synchronization is the monitor. This chapter describes these monitors and how they are used by the JVM. and describes the lock and unlock of the monitor from the JVM instruction set.

Monitoring Device (Monitors)

The Java monitor supports two types of thread synchronization: mutual exclusion (mutual exclusion) and collaboration (cooperation). Mutual exclusion, the JVM uses object Locks (objects Locks) to allow different threads to share data independently of each other without interfering with each other, and the JVM uses the wait and notify methods of class object to enable multiple threads to work together to accomplish a common goal.

The monitor is like a building with a special room that can only be occupied by one thread at a time, and the room usually contains some data. From a thread into the room until he leaves, he has exclusive access to any data in the room. Entering the monitoring building is called "entering the Monitor". Entering the special room is called "acquiring the Monitor". Occupying the room is called "Owning the Monitor". Leaving the room is called "releasing the Monitor". Leaving the whole building is called "exiting the Monitor".

In addition to monitoring the relevant data, the monitor monitors the relevant code (we call it the critical section (monitor regions)). The critical section is the block of code that we need to synchronize. The monitor enforces that only one thread at a time can execute the critical section code until the end (that is, the atomic operation, which is equivalent to the transaction in the database transaction either once or not). The only way a thread executes a critical section code is to get a monitor (acquiring the monitor).

When a thread executes to the beginning of a critical section, he is placed in the entry set of the entry set associated with the monitor. The entrance collection resembles the front corridor inside the monitoring building. If no thread is waiting in the entry set and no thread currently owns the monitor (owning), then the thread obtains the monitor (acquiring the monitor) and then continues to execute the critical section code. When the thread finishes executing the critical section code, he releases and exits the monitor (release and exit the monitor), and if the thread enters entry set, the monitor is already occupied by other threads, then the newly arrived thread must wait in the entry set. When the thread that owns the monitor finishes and exits the monitor, the newly arrived thread must compete with the other threads waiting in the entry set for the released monitor. There is only one that can be obtained.

Mutual exclusion (mutual exclusion) is generally used for access critical sections of multi-threaded mutexes. The mutex model is generally important when multiple threads share memory data or other resources.

Another synchronization model is collaboration (cooperation). Mutual exclusion is when multiple threads share data without interfering with each other, while collaboration is helping multiple threads to work together to accomplish a common goal.

Collaboration is important when a thread needs to reach a certain state of data and another thread is responsible for getting the data to that state. For example, a read thread might read data from buffer buffers, and another write thread would be responsible for populating the buffer with data. The read thread reads the condition that the buffer is not empty, and if the read thread finds that buffer is empty, then he must wait, and the write thread is responsible for populating the buffer if it is not full. So write a thread to write a little, read the thread a little.

This form is called the Wait andnotify Monitor in the JVM. (also called signal and Continue), this type of monitor can suspend itself by the wait method when a thread has a monitor and is executing. When a thread executes wait, he releases the monitor and enters the wait set. Self-suspending threads are awakened when and only after other threads have executed notify. However, the thread execution notify will continue to hold monitor until he releases the monitor himself (either executing wait or executing the Critical Zone Monitor region). After the Notify thread releases monitor, the waiting thread will regain monitor.

This JVM monitor is sometimes called the Signaland Continue Monitor, because a thread that executes notify (the signal) still holds the monitor to continue the critical section (Continue). After a certain period of time, the notifying thread releases monitor while the waiting thread resumes. Waiting line Chengtong often hangs itself because the data that is protected by the monitor has not yet reached the state in which the thread continues to work. Similarly, the notifying thread executes notify when he makes the protected data reach the desired state of the waiting thread. But because the notifying thread will continue, he may change the state of the data again so that the waiting thread still does not work. Another possibility is that the third thread obtains monitor after notify is released, and the third thread may change the state of the protected data. Therefore, the notifying thread emits a notify signal only as a hint to the waiting thread (the desired state may exist) rather than an absolute presence. Every time the waiting thread is reborn, he must also check the data state to decide whether to work forward. If the data is still unavailable, he will execute the wait again or give it up directly. This means that the check and operation must be atomic operations together.

is a description of the above monitor. In the middle of the rectangle there is only one thread, which is the owner of Monitor. The small rectangle on the left contains the entry set entry set. The small rectangle on the right contains wait set waiting set. Gray indicates the active state of the thread, and the suspended (blocked) state of the thread is dimmed.

The picture shows several doors marked with serial numbers, and the threads must pass through these doors to interact with the monitor. When a thread arrives at the beginning of the critical section, he enters the monitor through the gate ①. Find your position in the entry set. If there is currently neither a thread that owns the monitor nor any other thread waiting on the entry set, the thread quickly executes through the gate ② possession Monitor, and if there are other threads currently denouncing monitor, then the newly arrived thread must wait in the entry set and enter the block.

There are 3 threads in the entry set and 4 suspended in the wait set. They instruct the main thread to release the monitor before they come out. There are two ways to release monitor from the current host thread: The critical section is executed and the wait command is called. If he finishes the critical section, he will exit from the bottom of the door ⑤. If he executes wait, he will enter the wait set from the door ③.

If the predecessor host does not execute notify, only the threads in the EntrySet can compete for monitor. If notify is executed, then all blocking threads compete with monitor.

In the JVM, a thread can also select a time-out setting when it executes a wait. If there is a setting, no other thread will execute the notify,waiting thread before the time arrives to accept the notify signal from the JVM.

To say the point, the JVM chooses the next thread from entry set and wait set depends on the specific implementation of the JVM. Different JVM implementations are not the same. That is, programmers are not aware of. As a programmer, you can't rely on any specific choice algorithm or priority, you should try to write platform-independent programs. For example, you do not know the order in which the threads in the wait set are selected by the JVM, so you only use the Notify command when you are absolutely sure that only one thread is in the wait set. If there are more than one thread in the wait set, then you should use Notifyall. Otherwise, some threads may be blocked for a long time without execution or even always fail, because you do not know what the JVM's scheduling algorithm is.

Object Locking

Object Lock (The lock is what we call the implementation of the Monitor model)

In the JVM, each object and class is logically associated with a monitor. For an object, the associated monitor protects the object instance variable. For classes, monitor protects class member variables for classes.

To achieve the mutex capability of Monitor, the JVM has a lock (lock) associated with each class and object. A lock a moment only one thread can have. Thread Access object instances or class variables can be accessed without locking. But once a thread gets a lock, other threads cannot access the lock on the same data until the thread releases the lock. (Lock an object) is equivalent to getting the monitor associated with the object (acquiring the monitor))

Class lock is essentially an object lock. When the JVM loads each class, it creates an instance of Java.lang.Class, and when you lock a class, the class object is actually locked.

A single thread allows multiple locks of the same object. The JVM maintains a counter count of the number of times an object is locked for each object. The count of an object that is not locked is 0. When a thread obtains a lock for the first time, count increases by 1.

Each time a thread obtains a lock on the same object, count increases by 1. (Only the thread that has acquired the object lock allows the object to be locked again, and the internal lock can be re-entered; Other threads must wait until the lock is released to obtain the lock.) Each time the thread releases the lock, Count is reduced by 1, and the lock is available to other threads when count is 0 o'clock.

A lock is requested when the thread executes to the beginning of the critical section. There are two types of critical sections in the JVM: the synchronized block and the synchronized method. Each critical section is associated with an object reference. When a thread executes the first instruction in a critical section, he must obtain a lock on the associated object. When a thread leaves the synchronization block, no matter how it leaves, the lock is released.

Thread synchronization and Object locks inside JVM

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.