为什么静态和默认接口方法不能同步?
人们说synchronized是一个实现细节.那么,strictfp也是一个实现细节,但这并不妨碍在静态和默认接口方法上允许strictfp.
如果实现接口的类没有覆盖默认方法,则继承默认方法并使其已经同步可能非常方便.
我猜测synchronized(以及strictfp)不是继承的(我在这里吗?),但这并不能解释为什么strictfp也允许静态和默认接口方法.
解决方法
标记为synchronized的方法实际上是一个实现细节,并且不能由任何一个接口为其任何实现指定或控制.如Brian Goetz所解释的那样,它被故意排除在默认方法之外,因为它们本质上是危险的(强调我的):
…So,why are they dangerous? Synchronization is about locking. Locking is about coordinating shared access to mutable state. Each object should have a synchronization policy that determines which locks guard which state variables. (See Java Concurrency in Practice,section 2.4.)
…It is the class that owns the state that gets to determine that object’s synchronization policy. But interfaces do not own the state of the objects into which they are mixed in. So using a synchronized method in an interface assumes a particular synchronization policy,but one which you have no reasonable basis for assuming,so it might well be the case that the use of synchronization provides no additional thread safety whatsoever (you might be synchronizing on the wrong lock).