Overriding synchronized methods in Java

public synchronized void foo() {  // synchronized!
    // ...
};

Is essentially the same as:

public void foo() {
    synchronized (this) {  // synchronized!
        // ...
    }
};

The latter is more explicit, so I would generally suggest using that form. Or better using a lock that is a private field instead of the "outer" object.

So: 1. No. 2. Yes. 3. No. 4. Mark the method final and call a protected method that may be overridden.

public final void foo() {
    synchronized (this) {
        fooImpl();
    }
};
protected void fooImpl() {
    // ...
}

As ever, you may well be better off with delegation rather than subclassing.


Failing to use synchronized when overriding a synchronized method has the potential for causing runtime bugs. As a safeguard, there is an Eclipse checker you can turn on to detect this condition. The default is "ignore". "Warning" is also a valid choice. preferences

which will produce this message:

enter image description here

enter image description here