加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:48:15 所属栏目:Java 来源:网络整理
导读:参见英文答案 What is the reason why “synchronized” is not allowed in Java 8 interface methods?1个 为什么静态和默认接口方法不能同步? 人们说synchronized是一个实现细节.那么,strictfp也是一个实现细节,但这并不妨碍在静态和默认接口方法上允许str
参见英文答案 > 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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读