微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 为什么静态和默认接口方法不能同步但可以是strictfp?

参见英文答案 > What is the reason why “synchronized” is not allowed in Java 8 interface methods?1个
为什么静态和认接口方法不能同步?

人们说synchronized是一个实现细节.那么,strictfp也是一个实现细节,但这并不妨碍在静态和认接口方法上允许strictfp.

如果实现接口的类没有覆盖方法,则继承方法并使其已经同步可能非常方便.

我猜测synchronized(以及strictfp)不是继承的(我在这里吗?),但这并不能解释为什么strictfp也允许静态和认接口方法.

解决方法

strictfp关键字确保您的浮点运算 are consistent across all platforms. stricftp成为JVM的保证,您的浮点运算在所有平台上将是相同的,并且可以预期浮点运算是可移植的且一致的始终.

标记为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 举报,一经查实,本站将立刻删除。

相关推荐