Page 1 of 1

About Question enthuware.ocpjp.v8.2.1115 :

Posted: Fri Oct 09, 2015 3:20 am
by Martyjee
I would like to add something to the explanation with respect to Java 8:
Therefore, synchronized keyword can be applied only to a non-abstract method or a block of code appearing in a method or static or instance initialization blocks.
Consider the following interface:

Code: Select all

public interface Synchronizable {
    static void sync() { 
        synchronized (Synchronizable.class) { //no problem!
        }
    }

    static synchronized void deSync() { //will not compile!
    }

    default synchronized void defaultSync() { //will not compile!
    }
}
For some reason, the synchronized keyword cannot be applied to static non-abstract interface methods, as well as non-abstract default methods. However, it is possible to synchronize those methods using a lock on the class (Synchronizable.class). That is exactly what we expect to happen when we put the synchronized keyword in the method's signature. However, compilation fails if we do that.

Finally,
All methods in an interface are implicitly abstract.
is not a valid statement anymore since Java 8!

Kind regards,

Martijn

Re: About Question enthuware.ocpjp.v8.2.1115 :

Posted: Fri Oct 09, 2015 4:01 am
by admin
Fixed.
thank you for your feedback!

Re: About Question enthuware.ocpjp.v8.2.1115 :

Posted: Tue Oct 13, 2015 5:26 am
by Martyjee
I appreciate the fix.
However, to have a complete picture of the synchronized keyword w.r.t. Java 8, the explanation should be something like:

The synchronized keyword can be applied only to non-abstract methods that are defined in a class or a block of code appearing in a method or static or instance initialization blocks.

Re: About Question enthuware.ocpjp.v8.2.1115 :

Posted: Tue Oct 13, 2015 5:48 am
by admin
Done.
thanks again!