Home > Java > javaTutorial > What does Monitor mean? Introduction to Monitor in Java

What does Monitor mean? Introduction to Monitor in Java

不言
Release: 2019-05-14 11:44:24
Original
67451 people have browsed it


What does Monitor mean? Introduction to Monitor in Java

This article brings you what does Monitor mean? The introduction of Monitor in Java has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The concept of monitor

Monitor in English is also often translated as "monitor". Whether monitor is translated as "monitor" or "monitor", it is a comparison Obscure, through translated Chinese, it is impossible to achieve an intuitive description of monitor.
In this article "Operating System Synchronization Primitives", we introduce some synchronization primitives supported by the operating system when facing synchronization between processes/threads. Among them, semaphore semaphore and mutex mutex are the most popular ones. Important synchronization primitives.
When using basic mutex for concurrency control, programmers need to be very careful to control the down and up operations of the mutex, otherwise it will easily cause deadlock and other problems. In order to make it easier to write correct concurrent programs, a higher-level synchronization primitive monitor is proposed based on mutex and semaphore. However, it should be noted that the operating system itself does not support the monitor mechanism. In fact, monitor It belongs to the category of programming language. When you want to use monitor, first find out whether the language itself supports monitor primitive. For example, C language does not support monitor, and Java language supports monitor.
The general monitor implementation mode is that the programming language provides syntactic sugar in the syntax, and how to implement the monitor mechanism is the work of the compiler. This is what Java does.

The important feature of monitor is that only one process/thread can enter the critical section defined in the monitor at the same time, which enables the monitor to achieve mutual exclusion. But it is not enough to have mutual exclusion. Processes/threads that cannot enter the critical section of the monitor should be blocked and awakened when necessary. Obviously, as a synchronization tool, monitor should also provide such a mechanism for managing process/thread status. Think about why we think semaphore and mutex are error-prone in programming, because we need to personally manipulate variables and block and wake up processes/threads. The reason why the monitor mechanism is called a "higher-level primitive" is that it inevitably needs to shield these mechanisms from the outside and implement these mechanisms internally, so that people who use the monitor see a simple and easy-to-use interface.

Monitor basic elements

The monitor mechanism requires several elements to cooperate, namely:

  1. Critical section

  2. Monitor object and lock

  3. Condition variables and wait and signal operations defined on the monitor object.

The main purpose of using the monitor mechanism is to mutually exclude entry into the critical section. In order to block processes/threads that cannot enter the critical section, a monitor object is needed to assist. This monitor There will be corresponding data structures inside the object, such as lists, to save blocked threads; at the same time, because the monitor mechanism is essentially based on the basic primitive mutex, the monitor object must also maintain a mutex-based lock.
In addition, in order to be able to block and wake up the process/thread at the appropriate time, a condition variable needs to be introduced. This condition variable is used to determine when the "appropriate time" is. This condition can come from the logic of the program code, or It can be inside the monitor object. In short, the programmer has great autonomy in the definition of condition variables. However, since the monitor object uses an internal data structure to save the blocked queue, it must also provide two external APIs to allow the thread to enter the blocked state and wake up later, namely wait and notify.

Java language supports monitor

Monitor is a high-level primitive proposed by the operating system, but its specific implementation mode may be different in different programming languages. The following uses Java's monitor as an example to explain how monitor is implemented in Java.

Delineation of critical sections

In Java, the synchronized keyword can be used to modify instance methods, class methods and code blocks, as shown below:

/**
 * @author beanlam
 * @version 1.0
 * @date 2018/9/12
 */
public class Monitor {

    private Object ANOTHER_LOCK = new Object();

    private synchronized void fun1() {
    }

    public static synchronized void fun2() {
    }

    public void fun3() {
        synchronized (this) {
        }
    }

    public void fun4() {
        synchronized (ANOTHER_LOCK) {
        }
    }
}
Copy after login

Being synchronized key Word-modified methods and code blocks are the critical sections of the monitor mechanism.

monitor object

It can be found that when using the above synchronized keyword, you often need to specify an object to associate with it, such as synchronized(this), or synchronized(ANOTHER_LOCK), if synchronized is modified If it is an instance method, then its associated object is actually this. If it is a class method, then its associated object is this.class. In short, synchronzied needs to be associated with an object, and this object is the monitor object.
In the monitor mechanism, the monitor object plays the role of maintaining the mutex and defining the wait/signal API to manage thread blocking and wake-up.
The java.lang.Object class in the Java language is the object that meets this requirement. Any Java object can be used as the monitor object of the monitor mechanism.
Java objects are stored in memory and are divided into three parts, namely object header, instance data and alignment filling. In its object header, the lock identifier is saved; at the same time, the java.lang.Object class defines wait (), notify(), notifyAll() methods, the specific implementation of these methods relies on an implementation called ObjectMonitor mode, which is a set of mechanisms implemented within the JVM based on C. The basic principles are as follows:

What does Monitor mean? Introduction to Monitor in Java

When a thread needs to acquire the lock of an Object, it will be placed in the EntrySet to wait. If the thread acquires the lock, it will become the owner of the current lock. If according to the program logic, a thread that has acquired the lock lacks some external conditions and cannot continue (for example, the producer finds that the queue is full or the consumer finds that the queue is empty), then the thread can transfer the lock by calling the wait method. Release and enter the wait set to block and wait. At this time, other threads have the opportunity to obtain the lock and do other things, so that the external conditions that were not established before are established, so that the previously blocked threads can re-enter the EntrySet to compete for the lock. This external condition is called a condition variable in the monitor mechanism.

synchronized keyword

The synchronized keyword is an important tool used by Java at the syntax level to allow developers to easily perform multi-thread synchronization. To enter a method or code block modified by a synchronized method, the object lock of the Object bound to the synchronized keyword will first be obtained. This lock also restricts other threads from entering other synchronized code areas related to this lock.

Many articles and information on the Internet, when analyzing the principle of synchronized, basically say that synchronized is implemented based on the monitor mechanism, but few articles make it clear, and they are all vaguely mentioned.
Referring to the basic elements of Monitor mentioned earlier, if synchronized is implemented based on the monitor mechanism, what are the corresponding elements?
It must have a critical section. We can think of the critical section here as the P or V operation on the object header mutex. This is a critical section.
Which one does the monitor object correspond to? mutex? In short, the real monitor object cannot be found.
So I think the statement "synchronized is implemented based on the monitor mechanism" is incorrect and ambiguous.
The monitor mechanism provided by Java is actually formed by the cooperation of elements such as Object and synchronized. Even external condition variables are also a component. The underlying ObjectMonitor of the JVM is just a common mode used to assist in the implementation of the monitor mechanism, but most articles directly regard ObjectMonitor as the monitor mechanism.
I think it should be understood this way: Java's support for monitors is provided to developers at the granularity of the mechanism. That is to say, developers must use the synchronized keyword in combination with elements such as wait/notify of Object. He said that he used the monitor mechanism to solve a producer-consumer problem.



The above is the detailed content of What does Monitor mean? Introduction to Monitor in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template