About Question enthuware.ocpjp.v8.2.1115 :
Posted: Fri Oct 09, 2015 3:20 am
I would like to add something to the explanation with respect to Java 8:
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,
Kind regards,
Martijn
Consider the following interface: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.
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!
}
}
Finally,
is not a valid statement anymore since Java 8!All methods in an interface are implicitly abstract.
Kind regards,
Martijn