The premise

1. How is visibility implemented for Lock and Synchronzied?

Lock: using the volatile happens-before related rules, Java AbstractQueuedSynchronizer internal hold a volatile modified state variables:

  /** * The synchronization state. * /
    private volatile int state;
Copy the code

According to the volatile visibility rule, multiple threads always get the latest value of state when they read it. That is, the current thread’s locking and unlocking of a variable is visible to the next thread.

Synchronzied synchronized happens-before the lock is subsequently locked. Of course, you can also see how this works from a bytecode perspective:

public class Demo_01 {
    private final Object lock = new Object();

    public void test(a) {
        synchronized (lock) {
            // do sth....}}}Copy the code

Execute javap -verbose Demo_01 to intercept partial bytecode:

 Code:
      stack=2, locals=3, args_size=1
         0: aload_0
         1: getfield      #3                  // Field lock:Ljava/lang/Object;
         4: dup
         5: astore_1
         6: monitorenter
         7: aload_1
         8: monitorexit
         9: goto          17
        12: astore_2
        13: aload_1
        14: monitorexit
        15: aload_2
        16: athrow
        17: return

Copy the code

Look at lines 6 and 14 monitorenter and Monitorexit. The code that executes between these two instructions is: sequential, visible, atomic;

In a word: are the implementation of pipe procedures in concurrent programming;

Here are the differences from a programmer’s perspective:

Tip:

  • In an interview, they ask:
What does the keyword synchronized mean when referring to instance methods, static methods, and code blocks?
  • A:
  1. When modifying an instance method, lock the current object instance.

  2. When modifying a static method, lock the current class.

  3. When modifying a code block, locks the specified object.

  4. The lock of the current object/current class/specified object is required before entering the synchronized code/code block.