What if a static initializer in class X invokes a method in Y, but Y's static initializers invoke a method in X to set up its static values?

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

  •  11-12-2021
  •  | 
  •  

Question

This question is asked and explained in JAVA PROGRAMMING LANAGUAGE book.But i m not clear with explaination.

Can someone Explain it more clearly ?

Explaination in book is ::

This cyclic static initialization cannot be reliably detected during compilation because the code for Y may not be written when X is compiled. If cycles happen, X's static initializers will have been executed only to the point where Y's method was invoked. When Y, in turn, invokes the X method, that method runs with the rest of the static initializers yet to be executed. Any static fields in X that haven't had their initializers executed will still have their default values (false, '/u0000', zero, or null depending on their type).

Was it helpful?

Solution

Quite simply: if a thread is already initializing a class X when it requires class X to be initialized for another reason (e.g. because class Y uses something from it) then it just skips it. All the static variables have their default values.

For a precise description of what's going on, see the Java Language Specification, section 12.4.2. In particular:

If the Class object for C indicates that initialization is in progress for C by the current thread, then this must be a recursive request for initialization. Release LC and complete normally.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top