synchronized & inheritance

Hi all,

I try to explain it as short as possible:

public abstract class A {

...

public synchronized void aaa() {...}

public synchronized void bbb() {...}

...

}

public class B extends A {

...

public synchronized void ccc() {...}

public synchronized void ddd() {...}

...

}

Now I create instance of B:

b = new B();

Access to synchronized methods b.aaa(), b.bbb(), b.ccc(), b.ddd() is protected with the same lock of object b. In other words (maybe not-so-java-pro words) these methods are all synchronized together.

Is it correct?

Would it make a difference if A was not abstract class but instead just class (other the same)?

Thanks.

[752 byte] By [Skoreca] at [2007-10-3 3:00:19]
# 1

Yes, you are correct that all the methods would be synchronized together. If object b was in the middle of method b.aaa() it would prevent any other thread from calling method b.bbb(), b.ccc() or b.ddd() until b.aaa() returned. The abstractness of class A makes no difference, since the monitor for these methods is always b.

Brian

brian@cubik.caa at 2007-7-14 20:49:54 > top of Java-index,Core,Core APIs...
# 2

Just to reinforce what Brian said. A synchronized method acquires the lock of 'this', and 'this' doesn't change whether you are invoking a method of the actual class or an inherited one.

Note however that static synchronized methods in A and B would lock different objects: the Class object for A and the Class object for B, respectively.

davidholmesa at 2007-7-14 20:49:54 > top of Java-index,Core,Core APIs...