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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/java/121245.html

猜你在找的Java相关文章