Whats up with static memory in java?

Imports don’t correlate with any instructions in compiled code. They establish aliases for use at compile time only.

There are some reflective methods that allow the class to be loaded but not yet initialized, but in most cases, you can assume that whenever a class is referenced, it has been initialized.

Static member initializers and static blocks are executed as if they were all one static initializer block in source code order.

An object referenced through a static member variable is strongly referenced until the class is unloaded. A normal ClassLoader never unloads a class, but those used by application servers do under the right conditions. However, it’s a tricky area and has been the source of many hard-to-diagnose memory leaks—yet another reason not to use global variables.


As a (tangential) bonus, here’s a tricky question to consider:

public class Foo {
  private static Foo instance = new Foo();
  private static final int DELTA = 6;
  private static int BASE = 7;
  private int x;
  private Foo() {
    x = BASE + DELTA;
  }
  public static void main(String... argv) {
    System.out.println(Foo.instance.x);
  }
}

What will this code print? Try it, and you’ll see that it prints “6”. There are a few things at work here, and one is the order of static initialization. The code is executed as if it were written like this:

public class Foo {
  private static Foo instance;
  private static final int DELTA = 6;
  private static int BASE;
  static {
    instance = null;
    BASE = 0;
    instance = new Foo(); /* BASE is 0 when instance.x is computed. */
    BASE = 7;
  }
  private int x;
  private Foo() {
    x = BASE + 6; /* "6" is inlined, because it's a constant. */
  }
}

Leave a Comment