Does declaring a Java class strictfp mean methods it calls in other classes are also strictfp?

StackOverflow https://stackoverflow.com/questions/17052644

  •  31-05-2022
  •  | 
  •  

문제

As title really... if class X is declared strictfp and calls methods in class Y, will strictness be enforced, or does this only apply to X's own code?

Additionally, if I calculate a value in a strictfp class method and pass it into a non-strictfp method, is the value still 'safe' if no further calculations are done with it?

도움이 되었습니까?

해결책

As far as I understand strictfp is limited to scope marked with this keyword. This means that it causes calculations of marked class or method to be portable.

It cannot propagate the effect to referenced code. For example if foo() is strictfp but it calls bar() from some other class that is not strictfp, the calculations inside bar() will not be portable, but calculations inside foo() will be. So, if results of bar() are used in foo() the overall result might be not portable.

public strictfp double foo() {
    return bar() * 3.1415926;
}
public double bar() {
    return 2.718281828 * 2.0;
}

This result 2.718281828 * 2.0 is not portable, but its multiplication by 3.1415926 is.

다른 팁

From the Java Language Specification:

The effect of the strictfp modifier is to make all float or double expressions within the class declaration (including within variable initializers, instance initializers, static initializers, and constructors) be explicitly FP-strict.

[my emphasis]

It only applies to expressions in methods declared in that class.

From the jGuru article What is the strictfp modifier for? When would I consider using it?:

The strictfp keyword may be applied to both classes and methods. For classes (and interfaces), it specifies that all of the expressions in all of the methods of the class are FP-strict.

To answer your second question: yes, a floating point value will be "safe" once it's no longer subject to further calculations, since strictfp applies only to expressions.

Related: When should I use the "strictfp" keyword in java?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top