简体   繁体   中英

synchronized method of the inner class

If a method of an inner class is marked as synchronized, which lock is actually acquired for this method? The outer object or the inner object?

Initially, I think it is the inner object but when I saw a code snippet: sample inner class , stateMachine is not even the member of the inner class but is the member of the outer class, so I wonder maybe the lock acquired is the outer object?

Thank you

It will be synchronized on the Object the method is a member of.

public class SyncTest{
    class B{
        synchronized void runTest(){
            System.out.println("running");
        }
    }
    synchronized void check() throws Exception{
        B b = new B();
        new Thread( ()-> b.runTest() ).start();
        System.out.println("waiting");
        Thread.sleep(100);
        System.out.println("finished");
    }
    public static void main(String[] args) throws Exception {

        new SyncTest().check();
    }

}

This example, if runTest was synchronized on the outer object, the thread couldn't run until the check method finished. It is actually synchronized on the instance of the inner class though.

This is a race condition to see when "running" gets printed. It could be first, or after "waiting", and rarely ever but possibly after "finished".

We can modify our 'runTest' program to be synchronized on the outter instance.

synchronized( SyncTest.this ){
    System.out.println("running");
}

Now "running" will always be printed last because it has to wait for the 'check' method to finish since they're synchronized on the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM