JAVA lock Introduction (super detail)

Previous article describes JAVAsome of the concurrent use of locks and inside of introduction. At the same time, after also describes the opcode byte code, so that we first understand the instructions inside, where I also realize from the surface to explain the underlying operating under lock code.

(I want to learn programming from a small partner search circle T community , more and more industry-related industry information about free video tutorials. Oh, absolutely free!)

Lock object program:

package com.montos.detail;
public class SynchronizedDemo {
	public static void main(String[] args) {
		SynchronizedDemo demo = new SynchronizedDemo();
		demo.demo();
	}
	public void demo() {
		synchronized (this) {
			System.out.println("this is demo");
		}
	}
}

Decompile them:

public class com.montos.detail.SynchronizedDemo {
  public com.montos.detail.SynchronizedDemo();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: new           #2                  // class com/montos/detail/SynchronizedDemo
       3: dup
       4: invokespecial #3                  // Method "<init>":()V
       7: astore_1
       8: aload_1
       9: invokevirtual #4                  // Method demo:()V
      12: return
  public void demo();
    Code:
       0: aload_0
       1: dup
       2: astore_1
       3: monitorenter
       4: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
       7: ldc           #6                  // String this is demo
       9: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      12: aload_1
      13: monitorexit
      14: goto          22
      17: astore_2
      18: aload_1
      19: monitorexit
      20: aload_2
      21: athrow
      22: return
    Exception table:
       from    to  target type
           4    14    17   any
          17    20    17   any
}

Copy the code above to see the result of decompilation, we can see that there is an operation which is decompiled code monitorenter and monitorexit, the role of these two operations is the code:

  1. monitorenter: Each object is a monitor lock (monitor). When the monitor is occupied will be in a locked state, attempt to acquire ownership of the monitor thread execution monitorenter command, as follows:
  • If the number entering the monitor is 0, the thread enters the monitor, and then enter the number is set to 1, the thread is the owner of the monitor;
  • If the thread has occupied the monitor, only to re-enter, then enter the number into the monitor plus 1;
  • If another thread has occupied the monitor, the thread enters the blocked state into the monitor until the number is zero, then re-attempt to obtain ownership of the monitor;
  1. monitorexit: monitorexit execution thread must be objectref corresponding monitor owners. When the instruction is executed, enter the monitor number minus 1, minus 1 if entered number is 0, then the thread exits monitor, it is no longer the owner of this monitor. Other threads are blocked this monitor can attempt to take ownership of this monitor.

So as to achieve serial execution between threads, and I can see there are two monitorexit opcode: 1st synchronous exits normally release the lock; the lock is released 2nd exit to occur asynchronously; this is above it locked .

Lock method program:

public class SynchronizedDemo {
	public synchronized void method() {
		System.out.println("this is demo");
	}
}

Decompile:

public com.montos.detail.SynchronizedDemo();
    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
  public synchronized void method();
    descriptor: ()V
    flags: ACC_PUBLIC, ACC_SYNCHRONIZED
    Code:
      stack=2, locals=1, args_size=1
         0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
         3: ldc           #3                  // String this is demo
         5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
         8: return
      LineNumberTable:
        line 5: 0
        line 6: 8

Through the above decompile, we found two opcodes before was gone, the extra logo is ACC_SYNCHRONIZED, in fact, here is the code by the above two operations completed. This method is also more than just a common approach at the constant pool more ACC_SYNCHRONIZEDfields.

When the method is called, the call instruction will ACC_SYNCHRONIZED access method to check whether the flag is set, if set, execution thread will first obtain the monitor, get to perform the method body after successfully executing the method after their release monitor. During method execution, no other thread can no longer obtain the same monitor object.

Essentially no difference in the above two operations, only synchronization method is an implicit mode of operation, the JVM execution of two instructions to achieve mutual exclusion primitives mutex by calling the operating system, the blocked thread is hung since, waiting rescheduling leads to switch back and forth between "user mode and kernel mode" two states, have a greater impact on performance.

Lock key points:

Layout objects in memory are: object header, and an alignment padding instance data.
Here Insert Picture Description

  • Examples of data: data storing attribute information of the class, attribute information including the parent class;
  • Alignment padding: Since the virtual machine start-request object address must be an integer multiple of 8 bytes. Padding data need not be present, only for byte-aligned;
  • Object header: Java object header occupies two general machine code (32-bit virtual machine, a machine code is equal to 4 bytes, i.e. 32bit, the virtual machine 64, a machine code is 8 bytes, that is 64bit), but if the object is an array type, you will need three machine code, because the JVM virtual machine can determine the size of Java objects through metadata information Java objects, but can not confirm the size of the array of metadata from the array, Therefore, to record with a length of the array.

SynchronizedWith lock is the existence of Java objects in advance, then what is Javathe object head it? HotspotObject of virtual machine data mainly includes two parts: Mark Word(标记字段), Class Pointer(类型指针). Wherein Class Pointeris the object points to its class metadata pointer, the virtual machine is determined by the object class to which this is an example of a pointer, Mark Wordfor storing runtime data of the object itself, which is biased to achieve a lightweight lock and key locks.

That which we mainly noted that Mark Wordthe storage structure.
Here Insert Picture Description

Each Javaobject is created to come out with a handful of invisible lock, it is called internal locks or Monitorlock. Monitor objects exist in the object header of each Java object Mark Word(for storing pointers pointing), Synchronizedlock the lock is acquired in this manner, Java is why any object can be used as the reason for the lock, while notify/notifyAll/waitother methods use to Monitor lock object, you must use the synchronization code block.

Guess you like

Origin blog.csdn.net/wanghao112956/article/details/92977312