Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initialization by JVM

language: java
version: 12.0.2
String source code as follows:

 /* @implNote
 * The actual value for this field is injected by JVM. The static
 * initialization block is used to set the value here to communicate
 * that this static final field is not statically foldable, and to
 * avoid any possible circular dependency during vm initialization.
 */
static final boolean COMPACT_STRINGS;

static {
    COMPACT_STRINGS = true;
}

How to understand this sentence : 'The static initialization block is used to set the value here to communicate that this static final field is not statically foldable, and to avoid any possible circular dependency during vm initialization.'

like image 958
chachay Avatar asked Oct 08 '19 02:10

chachay


1 Answers

It's an implementation note for JVM implementers. It's not part of the public documentation and not of concern for developers that use java.lang.String.

But if you want to know:

Imagine that they had written:

static final boolean COMPACT_STRINGS = true;

Then it would have been a constant that the compiler could replace it with the value true wherever COMPACT_STRINGS was used (in the java.lang package only, because it's a package-local scoped variable)

By giving it the value true in a static initializer, the compiler doesn't know anymore that it's a constant and all code that uses it, has to look up the actual value that it has at runtime.

In this case, that is useful, because the JVM changes this value at runtime (even though it's final, the JVM can still change it), as the implementation note mentions.

like image 98
Erwin Bolwidt Avatar answered Nov 15 '22 21:11

Erwin Bolwidt