The strictfp Keyword in Java – Java 中的 strictfp 关键字

最后修改: 2019年 11月 13日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

By default, the floating-point computations in Java are platform-dependent. And so, the floating-point outcome’s precision depends on the hardware in-use.

默认情况下,Java中的浮点计算是与平台相关的。因此,浮点结果的精度取决于正在使用的硬件。

In this tutorial, we’ll learn how to use strictfp in Java to ensure platform-independent floating-point computations.

在本教程中,我们将学习如何在Java中使用strictfp来确保浮点计算与平台无关。

2. strictfp Usage

2.strictfp使用方法

We can use the strictfp keyword as a non-access modifier for classes, non-abstract methods or interfaces:

我们可以使用strictfp关键字作为类、非抽象方法或接口的非访问修改器。

public strictfp class ScientificCalculator {
    ...
    
    public double sum(double value1, double value2) {
        return value1 + value2;
    }

    public double diff(double value1, double value2) { 
        return value1 - value2; 
    }
}

public strictfp void calculateMarksPercentage() {
    ...
}

public strictfp interface Circle {
    double computeArea(double radius);
}

When we declare an interface or a class with strictfp, all of its member methods and other nested types inherit its behavior.

当我们用strictfp声明一个接口或类时,它的所有成员方法和其他嵌套类型都继承其行为。

However, please note that we’re not allowed to use strictfp keyword on variables, constructors or abstract methods.

然而,请注意,我们不允许在变量、构造函数或抽象方法上使用strictfp关键字。

Additionally, for cases when we have a superclass marked with it, it won’t make our subclass inherit that behavior.

此外,对于我们有一个超类标记的情况,它不会让我们的子类继承这个行为。

3. When to Use?

3.何时使用?

Java strictfp keyword comes handy whenever we care a great deal about the deterministic behavior of all floating-point computations:

当我们非常关心所有浮点计算的确定性行为时,Java的strictfp关键字就很方便。

@Test
public void whenMethodOfstrictfpClassInvoked_thenIdenticalResultOnAllPlatforms() {
    ScientificCalculator calculator = new ScientificCalculator();
    double result = calculator.sum(23e10, 98e17);
    assertThat(result, is(9.800000230000001E18));

    result = calculator.diff(Double.MAX_VALUE, 1.56);
    assertThat(result, is(1.7976931348623157E308));
}

Since the ScientificCalculator class makes use of this keyword, the above test case will pass on all hardware platforms. Please note that if we don’t use it, JVM is free to use any extra precision available on the target platform hardware.

由于ScientificCalculator类使用了这个关键字,上述测试案例将在所有硬件平台上通过。请注意,如果我们不使用它,JVM可以自由使用目标平台硬件上的任何额外精度。

A popular real-world use-case for it is a system performing highly-sensitive medicinal calculations.

它在现实世界中的一个流行的用例是一个进行高度敏感的医药计算的系统。

4. Conclusion

4.总结

In this quick tutorial, we talked about when and how to use the strictfp keyword in Java.

在这个快速教程中,我们谈到了何时以及如何在Java中使用strictfp关键字。

As usual, all the presented code samples are available over on GitHub.

像往常一样,所有介绍的代码样本都可以在GitHub上找到