为什么静态和默认接口方法不能同步?
人们说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).
原文地址:https://www.jb51.cc/java/121245.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。