简体   繁体   中英

Java: synchronize on superclass method

abstract class Basic (){
    public synchronized void basicMethod(String string){
        //Some actions here
    }
}

public class A extends Basic{
    public void aMethod(){
        //Some actions here
    }
}

public class B extends Basic{
    public void bMethod(){
        //Some actions here
    }
}

Basic a = new A();
Basic b = new B();

a.basicMethod(); // acquires lock
b.basicMethod(); //Same lock?

In other words - lock is related to concrete Object or Super class important too?

Different locks. A synchronized instance method synchronizes on the monitor associated with that particular object instance , so each of a and b has its own monitor.

If you had

abstract class Basic (){
    public synchronized void basicMethod(String string){
        //Some actions here
    }
}

public class A extends Basic{
    public synchronized void aMethod(){
        //Some actions here
    }
}

then calls to a.basicMethod() and a.aMethod() would lock the same monitor.

Though both a & b acquire a lock, these locks are associated to the object reference. So a & b will both be able to enter their synchronized region at the same point by acquiring different locks.

In other words - lock is related to concrete Object or Super class important too?

The lock is related to the object instance.

As far as I know, a lock is held on an object reference, not on the class definition. This means that those would be two different locks, as they are not held on the same object reference. Remember, every object in Java is a subclass of the Object class, so if it were the case that it locks on the highest superclass, it would only ever be possible to have one lock in a program.

There are different lock, as lock is held on a object . Javadoc says

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Basic a = new A();
Basic b = new B();

Each one a and b have different object reference so have different locks thus call to synchornized method with two different locks will happan.

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