search
HomeJavajavaTutorialWhat does Monitor mean? Introduction to Monitor in Java


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) {
        }
    }
}

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!

Statement
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
How does the JVM handle differences in operating system APIs?How does the JVM handle differences in operating system APIs?Apr 27, 2025 am 12:18 AM

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

How does the modularity introduced in Java 9 impact platform independence?How does the modularity introduced in Java 9 impact platform independence?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

What is bytecode, and how does it relate to Java's platform independence?What is bytecode, and how does it relate to Java's platform independence?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

Why is Java considered a platform-independent language?Why is Java considered a platform-independent language?Apr 27, 2025 am 12:03 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),whichexecutesbytecodeonanydevicewithaJVM.1)Javacodeiscompiledintobytecode.2)TheJVMinterpretsandexecutesthisbytecodeintomachine-specificinstructions,allowingthesamecodetorunondifferentp

How can graphical user interfaces (GUIs) present challenges for platform independence in Java?How can graphical user interfaces (GUIs) present challenges for platform independence in Java?Apr 27, 2025 am 12:02 AM

Platform independence in JavaGUI development faces challenges, but can be dealt with by using Swing, JavaFX, unifying appearance, performance optimization, third-party libraries and cross-platform testing. JavaGUI development relies on AWT and Swing, which aims to provide cross-platform consistency, but the actual effect varies from operating system to operating system. Solutions include: 1) using Swing and JavaFX as GUI toolkits; 2) Unify the appearance through UIManager.setLookAndFeel(); 3) Optimize performance to suit different platforms; 4) using third-party libraries such as ApachePivot or SWT; 5) conduct cross-platform testing to ensure consistency.

What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.