How to Use synchronized in static methods

Source: Internet
Author: User
Implementation of synchronized

synchronizedThere are two types:

  1. synchronized method
  2. synchronized block

The two implementation methods are different. The JVM specification writes that the compiled synchronized method hasAcc_staticThat is, when the JVM method call command (The Method Invocation instruction) FromThe run-time Contant poolWhen this method is found in, it is known that it is a synchronized method, so the lock operation is controlled by method calls and return instructions.
The synchronized block lock is composedMonitorenterAndMonitorexitThese two commands are used for control.


You can use the javap command to "Disassemble" the class file.


Java code:

public class StaticMethodTest {    public static synchronized void staticMethod() { }    public static void staticMethod1() {        synchronized (StaticMethodTest.class) {        // ...    }    }    public void memberMethod() { } }


Compile it into a class file and execute

javap -verbose StaticMethodTest


The output results of the two static methods are

public static synchronized void staticMethod();  descriptor: ()V  flags: ACC_PUBLIC, ACC_STATIC, ACC_SYNCHRONIZED  Code:    stack=0, locals=0, args_size=0       0: return    LineNumberTable:      line 2: 0
public static void staticMethod1();  descriptor: ()V  flags: ACC_PUBLIC, ACC_STATIC  Code:    stack=2, locals=2, args_size=0       0: ldc           #2                  // class StaticMethodTest       2: dup       3: astore_0       4: monitorenter       5: aload_0       6: monitorexit       7: goto          15      10: astore_1      11: aload_0      12: monitorexit      13: aload_1      14: athrow      15: return    Exception table:       from    to  target type           5     7    10   any          10    13    10   any


In fact, the synchronized implementation methods are the same regardless of static methods or member methods. What is the relationship between classes and objects?


Class and Object


The first thing you need to know isHow did the class come from?.


After JVM obtains the class file compiled by the compiler, it first loads the file into the memory. Of course, the class file will have its own format.ClassloaderTo parse the file content. The parsed content will be represented by an instance-Class Object of the class. This object can be expressed through the Java

ClassName.class

.


That is to say, the class object is a class instance, and the object is a classname instance. Both class and classname are types. classname is defined by the class keyword, while class is a built-in type.


Therefore, the Synchronized Method of the member method is equivalent to synchronized (this) block, that is, the following two methods are equivalent.

public synchronized void fun1() {    // do something here}public synchronized void fun2() {    synchronized (this) {    // do something here    }}

The member method belongs to this, while the static method belongs to class object. The Synchronized Method of the static method is equivalent to the synchronized block in the following form.

public static synchronized void fun2() {    synchronized (ClassName.class) {    // do something here    }}

Verification Code

Three static methods are defined with Different lock mechanisms, and each method is an endless loop. Then define three threads to execute and call three methods respectively.

import java.util.concurrent.*;public class SynchronizedTest {    private static Object lock = new Object();    public synchronized static void fun() {        while (true) {            System.out.println("in fun");        try {            TimeUnit.MILLISECONDS.sleep(500);        } catch (InterruptedException e) {            e.printStackTrace();        }    }    }    public static void fun1() {        synchronized (SynchronizedTest.class) {            while (true) {                System.out.println("in fun1");                try {                    TimeUnit.MILLISECONDS.sleep(500);            } catch (InterruptedException e) {                    e.printStackTrace();            }            }        }    }    public static void fun2() {        synchronized (lock) {            while (true) {                System.out.println("in fun2");                try {                    TimeUnit.MILLISECONDS.sleep(500);            } catch (InterruptedException e) {                    e.printStackTrace();            }            }    }    }    public static void main(String[] args) {        new Thread() {        @Override        public void run() {            fun();        }    }.start();        new Thread() {        @Override        public void run() {            fun1();        }    }.start();        new Thread() {        @Override        public void run() {            fun2();        }    }.start();    }}

The running result isIn funAndIn fun2Alternate appearance, that is, noIn fun1.
As long as the thread running fun does not hand over the lock, fun1 cannot be used because they all share the Lock of Class Object.

How to Use synchronized in static methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.