8

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.'

John3136
  • 27,345
  • 3
  • 44
  • 64
Xiu
  • 170
  • 6
  • Good question! This can be a start: https://en.wikipedia.org/wiki/Constant_folding But I have no idea about "circular dependency during vm initialization". – Alex 75 Oct 22 '19 at 20:43
  • @Alex 75 In my idea, if they had written like this: 'static final boolean COMPACT_STRINGS = true'. It can still avoid any possible circular dependency, because 'COMPACT_STRINGS' has been given a determined value. But it couldn't to avoid statically foldable. – Xiu Nov 01 '19 at 01:55

1 Answers1

7

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.

Erwin Bolwidt
  • 28,093
  • 15
  • 46
  • 70
  • can you explain the part `even though it's final, the JVM can still change it` on why JVM can change it? I got confuse on how JVM manages to change constant variables. – Francis ask question Oct 08 '19 at 03:26
  • 1
    @Francisaskquestion It's the JVM that makes it final, and it can break the rules it sets for the applicaion. – user207421 Oct 08 '19 at 03:32
  • @user207421 ahh then with some knowledge on JVM, it can also alter other variables? – Francis ask question Oct 08 '19 at 03:39
  • 1
    The JVM can do it. There may be tricks using reflection and/or unsafe access that work in current JVM's that allows an application to do it, but these may (and will likely considering Oracle's direction) no longer work in future versions of the JVM. – Erwin Bolwidt Oct 08 '19 at 04:04
  • 1
    @Francisaskquestion The JVM can do whatever it likes. – user207421 Oct 08 '19 at 04:43