interface Interface1 {
default void method1() {
synchronized (this) {
// Something
}
}
static void method2() {
synchronized (Interface1.class) {
// Something
}
}
}
我将获得完整的同步语义,可以在类中使用。但是,我不能在方法声明上使用synchronized
修饰符:
interface Interface2 {
default synchronized void method1() {
// ^^^^^^^^^^^^ Modifier 'synchronized' not allowed here
}
static synchronized void method2() {
// ^^^^^^^^^^^^ Modifier 'synchronized' not allowed here
}
}
现在,人们可以争论除了Interface2
对method1()
和method2()
建立了一个合同,比Interface1
更加强大以外,这两个接口的行为方式是相同的。当然,我们也可以认为default
实现不应该对具体实现状态做出任何假设,或者这样一个关键字根本无法发挥作用。
问题:
JSR-335专家组为什么决定不支持接口方法上的synchronized
?
default synchronized
的解释,但不一定适用于static synchronized
,尽管我认为后者可能是出于一致性考虑而被省略。 - Lukas Edersynchronized
修饰符可能会在子类中被覆盖,因此只有在存在final默认方法时才会有影响。(你的另一个问题) - skiwisynchronized
的方法,从而有效地删除同步。我不会感到惊讶,如果不支持synchronized
和不支持final
是相关的,也许是因为多重继承(例如继承void x()
和synchronized void x()
等)。但这只是猜测。如果有权威的原因,我很好奇。 - Lukas Edersuper
,这需要完全重新实现并可能需要访问私有成员。顺便说一下,这些方法之所以被称为“defenders”(守护者),是为了方便添加新方法。 - bestsss