The Coordinator
The Coordinator

Reputation: 13137

What is inlineable as a run-time constant?

Must it be private + static + final to be inlineable as a compile-time constant?

What can be inlinable as a run-time constant?

How about also:

private final ...
static final ...
final ...

Upvotes: 0

Views: 159

Answers (4)

Stephen C
Stephen C

Reputation: 719336

The JLS 4.12.4 specifies what a "constant variable" is. Basically, the requirement is that it must be final, the type is a primitive type or String, and the value must be a constant expression (15.28).

The value of a constant variable will be inlined by the bytecode compiler.

The JLS rules make no distinction between static or not, or between different access modifiers.


But public static final can be changed through reflection, so is it compile-time final?

Yes. In fact, reflective changes to constant variables have no effect:

"Even then, there are a number of complications. If a final field is initialized to a constant expression (§15.28) in the field declaration, changes to the final field may not be observed, since uses of that final field are replaced at compile time with the value of the constant expression." - JLS 17.5.3


What can be inlinable as a run-time constant?

Interesting question. I've not seen that issue mentioned directly in the JLS. However, clearly reflection could come into this (given what JLS 17.5.3 says).

One case where inlining would be allowed (if the JIT compiler could handle it) is a local variable that is either final or effectively final, and that has initializer that the JIT compiler can deduce is always the same. The overarching constraint is that runtime inlining must not change the observable behaviour of the program. (We don't need to consider reflection here because local variables cannot be accessed or changed via reflection.)

Upvotes: 2

Durandal
Durandal

Reputation: 20069

The access modifier has no effect on inlining.

What matters is that the value comes from a constant expression (http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28) and that its of a suitable type (primitive or String).

And although one can change final assignments by several means (the simplest is recompile the containing class with a new value), they are still treated as constants if above restrictions are upheld. So even public final static's can be (and frequently are) compile time inlined.

Upvotes: 2

Chris Thompson
Chris Thompson

Reputation: 35598

Any field marked as static final cannot be changed at runtime*, even with reflection and will be inlined.

*The caveat is I believe you can do this with unsafe operations.

Upvotes: 0

Simon
Simon

Reputation: 1605

The constant can be private or public depending on your needs but you should use static + final.

So...

private static final

Or...

public static final

Upvotes: 0

Related Questions