Welcome to The seventh article in a series on Concurrency.

In previous articles, we have experimented with the use of synchronized and given a brief introduction to the concepts and principles of locking. However, as you’ve probably noticed, one concept that seems to go hand in hand with the concepts of synchronized and lock, and many people like to ask the difference between them: Monitor.

So, after you’ve talked about synchronized and locks, the text will tell you about Monitor, revealing the open secrets between them, and hopefully you won’t be confused.

The first thing you need to understand is that Monitor, as a synchronization mechanism, is not specific to Java, but Java implements it.

To understand the abstract concept of Monitor concretely, let’s first examine a common scenario around us.

I. Understanding Monitor from the queuing mechanism of hospitals

I’m sure you’ve been to a hospital in the past. When we go to the hospital, it goes something like this:

  • First of all, we register at the reception desk of the outpatient lobby or the self-registration machine.
  • Then, after the registration, we found the correspondingClinic visits:
    • Only one patient can visit the clinic at a time;
    • If the clinic is idle at this time, enter the clinic directly;
    • If there are patients in the clinic at this time, then we enter the waiting room and wait for the call;
  • At the end of the treatment, out of the waiting room, waiting room the next patient into the room.

This procedure must be familiar to you, and it must be easy to understand. We made a diagram to show the following:

If you look closely at the process in this picture, if you understand the process, you understand the Monitor. Is it that simple? Don’t doubt yourself, yes. You already understand the Monitor mechanism!

Don’t underestimate this mechanism, it is a manifestation of wisdom in life. In this treatment mechanism, it plays two key roles:

  • Mutual exclusion: Allowing only one patient at a time into the waiting room;
  • When a patient in the clinic is finished, the next patient in the waiting area can be notified.

Got it? The process that you go through in the hospital is almost identical to the mechanism that Monitor uses. Another way to describe Monitor’s role in computer science:

  • Mutual exclusion: Allow only one thread at a time to enter a critical section;
  • Cooperation: When a thread in a critical section finishes execution and meets certain conditions, it can notify other waiting threads to enter.

In the process of treatment, the outpatient hall, the consultation room and the waiting room correspond to the three key concepts in Monitor. Among them:

  • Outpatient lobby: all threads to be entered must register at ** Entry Set ** to be qualified;
  • Consultation Room: a Special Room where only one thread can enter at a time.
  • Waiting room: When the waiting room is busy, enter the Wait Set.

Let’s tweak the above diagram to see what Monitor looks like in Java:

By contrast, you already intuitively understand the Monitor mechanism. Synchronized, on second thought, is an implementation of Monitor. In Java, each object is associated with a monitor.

2, synchronized source sense Monitor

Since synchronized is an implementation of Monitor, let’s write some minimalist code to give you a sense of what synchronized is all about.

This code is extremely simple, but sufficient, and we use the synchronized keyword in the code:

public class SyncMonitorDemo {
    public static void main(String[] args) {
        Object o = new Object();
        synchronized (o) {
            System.out.println("locking..."); }}}Copy the code

Javac syncMonitorDemo. Java and javap -v SyncMonitorDemo.class, respectively, will give you bytecode that looks like this:

Classfile SyncMonitorDemo.class Last modified May 26, 2021; size 684 bytes MD5 checksum e366920f22845e98c45f26531596d6cf Compiled from "SyncMonitorDemo.java" public class cn.tao.king.juc.execises1.SyncMonitorDemo minor version: 0 major version: 49 flags: ACC_PUBLIC, ACC_SUPER Constant pool: #1 = Methodref #2.#22 // java/lang/Object."<init>":()V #2 = Class #23 // java/lang/Object #3 = Fieldref #24.#25 // java/lang/System.out:Ljava/io/PrintStream; #4 = String #26 // locking... #5 = Methodref #27.#28 // java/io/PrintStream.println:(Ljava/lang/String;) V #6 = Class #29 // cn/tao/king/juc/execises1/SyncMonitorDemo #7 = Utf8 <init> #8 = Utf8 ()V #9 = Utf8 Code #10 = Utf8 LineNumberTable #11 = Utf8 LocalVariableTable #12 = Utf8 this #13 = Utf8 Lcn/tao/king/juc/execises1/SyncMonitorDemo; #14 = Utf8 main #15 = Utf8 ([Ljava/lang/String;)V #16 = Utf8 args #17 = Utf8 [Ljava/lang/String; #18 = Utf8 o #19 = Utf8  Ljava/lang/Object; #20 = Utf8 SourceFile #21 = Utf8 SyncMonitorDemo.java #22 = NameAndType #7:#8 // "<init>":()V #23 = Utf8 java/lang/Object #24 = Class #30 // java/lang/System #25 = NameAndType #31:#32 // out:Ljava/io/PrintStream; #26 = Utf8 locking... #27 = Class #33 // java/io/PrintStream #28 = NameAndType #34:#35 // println:(Ljava/lang/String;)V #29 = Utf8 cn/tao/king/juc/execises1/SyncMonitorDemo #30 = Utf8 java/lang/System #31 = Utf8 out #32 = Utf8 Ljava/io/PrintStream; #33 = Utf8 java/io/PrintStream #34 = Utf8 println #35 = Utf8 (Ljava/lang/String;)V { public cn.tao.king.juc.execises1.SyncMonitorDemo(); descriptor: ()V flags: ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return LineNumberTable: line 3: 0 LocalVariableTable: Start Length Slot Name Signature 0 5 0 this Lcn/tao/king/juc/execises1/SyncMonitorDemo; public static void main(java.lang.String[]); descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=4, args_size=1 0: new #2 // class java/lang/Object 3: dup 4: invokespecial #1 // Method java/lang/Object."<init>":()V 7: astore_1 8: aload_1 9: dup 10: astore_2 11: monitorenter 12: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 15: ldc #4 // String locking... 17: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 20: aload_2 21: monitorexit 22: goto 30 25: astore_3 26: aload_2 27: monitorexit 28: aload_3 29: athrow 30: return Exception table: from to target type 12 22 25 any 25 28 25 any LineNumberTable: line 5: 0 line 6: 8 line 7: 12 line 8: 20 line 9: 30 LocalVariableTable: Start Length Slot Name Signature 0 31 0 args [Ljava/lang/String; 8 23 1 o Ljava/lang/Object; } SourceFile: "SyncMonitorDemo.java"Copy the code

Javap is a disassembly command that comes with the JDK. You can ignore all the unnecessary information and find the following code directly in the results:

11: monitorenter 12: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 15: ldc #4 // String locking... 17: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;) V 20: aload_2 21: monitorexitCopy the code

Read the Monitorenter and monitorexit commands, and trust your wisdom to see through everything.

That’s all the text. Congratulations on getting another star ✨

The teacher’s trial

  • Write a paragraph containingsynchronizedKeyword code usedjavapCommand to observe the result.

Further reading and references

  • “King concurrent course” outline and update progress overview

About the author

Pay attention to [technology 8:30], get the article updates in time. Pass on quality technical articles, record the coming-of-age stories of ordinary people, and occasionally talk about life and ideals. 8:30 in the morning push author quality original, 20:30 in the evening push industry depth good article.

If this article is helpful to you, welcome to like, follow, supervise, we together from bronze to king.