How the compiler deals with cyclic static initialization

H

Hongzheng Wang

Hi, everyone,
I'm a newbie for Java. When I read the `The Java Programming
Language', I can't understand the discussion about `cyclic
static initialization' on page 51:

What if a static initializer in class X invokes a method in Y,
but Y's static initializer invoke a method in X to set up its
static values?
.......
If cycles happen, X's static initializer 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 oft the
static initializers yet to be executed.

I don't know the meaning of the second paragraph. Can anyone give
me a clearer explaination about it?

Thank you very much!
 
M

Michael Borgwardt

Hongzheng said:
What if a static initializer in class X invokes a method in Y,
but Y's static initializer invoke a method in X to set up its
static values?
......
If cycles happen, X's static initializer 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 oft the
static initializers yet to be executed.

I don't know the meaning of the second paragraph. Can anyone give
me a clearer explaination about it?

public class Foo{
static int myBar = Bar.getBar();
static int wiggle = Baz.methodThatDoesNotReturnAConstant();

public static int getFoo()
{
return wiggle;
}
}

public class Bar{
static int myFoo = Foo.getFoo();

public static int getBar()
{
return 42;
}
}

Now when Foo is loaded, it first calls Bar.getBar(). To do this, Bar is loaded and during
its initialization, it calls Foo.getFoo(), which returns the value of wiggle.
But since Foo's initialization is still stuck on the getBar() call and has not yet
progressed to the point where wiggle is assigned a meaningful value, wiggle is still 0
and that's what Bar stores in myFoo. If, on the other hand, Bar is loaded *first*,
then myFoo will be set to the proper value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top