Table of Contents
The concept of monitor
Monitor basic elements
Java language supports monitor
Delineation of critical sections
monitor object
synchronized keyword
Home Java javaTutorial What does Monitor mean? Introduction to Monitor in Java

What does Monitor mean? Introduction to Monitor in Java

Sep 17, 2018 pm 03:12 PM
java monitor


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!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Affordable Xiaomi Gaming Monitor G24i makes global debut with 180 Hz display and AMD FreeSync Affordable Xiaomi Gaming Monitor G24i makes global debut with 180 Hz display and AMD FreeSync Sep 11, 2024 am 06:39 AM

The Xiaomi Gaming Monitor G24i has made its global debut, and it's the most affordable option in the new lineup. It has an FHD IPS screen that the company claims is ideal for competitive gamers. The 23.8-inch panel has a 180 Hz refresh rate and 1 ms

IFA 2024 | Nitro GS272U M debuts as Acer\'s latest take on the smart gaming monitor IFA 2024 | Nitro GS272U M debuts as Acer\'s latest take on the smart gaming monitor Sep 05, 2024 am 06:41 AM

The NitroGS272U M has joined theAcer CS322Qin being introduced as a smart monitor atIFA 2024- however, theformer has the more gamer-like stand of itsGA-seriespredecessors. It also has a smaller 27-inch display - although the glare-free WQHD IPS panel

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles