Question
What is the reason why the JSR-335 expert group decided not to support synchronized on interface methods?
interface Interface2 {
default synchronized void method1() {
// Not allowed
}
static synchronized void method2() {
// Not allowed
}
}
Answer
In Java 8, the introduction of default and static methods in interfaces brought significant changes to how behaviors are defined in interface types. However, the decision by the JSR-335 expert group to disallow the use of the synchronized modifier in interface method declarations was influenced by several factors, most importantly design principles aimed at ensuring flexibility and clarity in interface implementations.
interface Interface1 {
default void method1() {
synchronized (this) {
// Implementation logic
}
}
static void method2() {
synchronized (Interface1.class) {
// Implementation logic
}
}
}
Causes
- **State Management:** Interface methods should ideally be stateless. Allowing synchronized on interface methods suggests that there are shared resources (state) being managed, which contradicts the purpose of interfaces as contracts for behavior, not stateful operations.
- **Implementation Complexity:** Adding synchronized to interface methods could lead to complex behavior where concrete classes have to manage the synchronization differently depending on the interface. This might confuse developers and make it hard to maintain code, especially in multi-thread environments.
- **Behavioral Contracts:** The primary role of an interface is to define a contract that implementing classes must follow. By allowing synchronized in an interface, it would impose unnecessary obligations on implementing classes that may not require synchronization.
Solutions
- **Use of Default Methods:** Developers can still achieve synchronization by using default methods in interfaces, as shown in the provided code snippets. By synchronizing the code within the method blocks rather than at the method level, one retains the ability to control access without breaking the interface contract.
- **Concrete Class Control:** Implementing classes can choose how to handle synchronization according to their needs, ensuring a clear separation of behavior definition (interfaces) from behavior implementation (concrete classes).
Common Mistakes
Mistake: Assuming interface methods can manage state with synchronization.
Solution: Remember that interfaces should focus on behavior contracts rather than state. Use default methods for managing implementation-specific behavior.
Mistake: Implementing synchronized methods in interfaces causing confusion in multi-threaded environments.
Solution: Design interfaces with the understanding that synchronization should typically be handled in the implementing classes, not in the method contract.
Helpers
- Java 8
- synchronized modifier
- interface methods
- JSR-335
- default methods
- multi-threading
- synchronization in Java