Java Secret: Loading and unloading static fields.

Overview

To start with it is natural to assume that static fields have a special life cycle and live for the life of the application. You could assume that they live is a special place in memory like the start of memory in C or in the perm gen with the class meta information.

However, it may be surprising to learn that static fields live on the heap, can have any number of copies and are cleaned up by the GC like any other object.

This follows on from a previous discussion; Are static blocks interpreted?

Loading static fields

When a class is obtained for linking it may not result in the static block being intialised.

A simple example
public class ShortClassLoadingMain {
    public static void main(String... args) {
        System.out.println("Start");
        Class aClass = AClass.class;
        System.out.println("Loaded");
        String s= AClass.ID;
        System.out.println("Initialised");
    }
}

class AClass {
    static final String ID;
    static {
        System.out.println("AClass: Initialising");
        ID = "ID";
    }
}
prints
Start
Loaded
AClass: Initialising
Initialised
You can see you can obtain a reference to a class, before it has been initialised, only when it is used does it get initialised.

Loading multiple copies of a static field

Each class loader which loads a class has its own copy of static fields. If you load a class in two different class loaders these classes can have static fields with different values.

Unloading static fields

static fields are unloaded when the Class' ClassLoader is unloaded. This is unloaded when a GC is performed and there are no strong references from the threads' stacks.

Putting these two concepts together

Here is an example where a class prints a message when it is initialised and when its fields are finalized.
class UtilityClass {
    static final String ID = Integer.toHexString(System.identityHashCode(UtilityClass.class));
    private static final Object FINAL = new Object() {
        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println(ID + " Finalized.");
        }
    };

    static {
        System.out.println(ID + " Initialising");
    }
}
By loading this class repeatedly, twice at a time
for (int i = 0; i < 2; i++) {
                cl = new CustomClassLoader(url);
                clazz = cl.loadClass(className);
                loadClass(clazz);

                cl = new CustomClassLoader(url);
                clazz = cl.loadClass(className);
                loadClass(clazz);
                triggerGC();
            }
        }
        triggerGC();
you can see an output like this
1b17a8bd Initialising
2f754ad2 Initialising

-- Starting GC
1b17a8bd Finalized.
-- End of GC

6ac2a132 Initialising
eb166b5 Initialising

-- Starting GC
6ac2a132 Finalized.
2f754ad2 Finalized.
-- End of GC


-- Starting GC
eb166b5 Finalized.
-- End of GC

In this log, two copies of the class are loaded first. The references to the first class/classloader are overwritten by references to the second class/classloader. The first one is cleaned up on a GC, the second one is retained. On the second loop, two more copies are initialised. The forth one is retained, the second and third are cleaned up on a GC. Finally the forth copy of the static fields are cleaned up on a GC when they are no longer references.

The Code

The first example - ShortClassLoadingMain The second example - LoadAndUnloadMain

Comments

  1. comment is not about this post.
    I have a question.

    1) while(i!=i+0){} (2) while(i==i+1)
    when this two loop will run infinite times...
    declare and initialize i.

    thanks in advance.

    ReplyDelete
  2. @Ajay, You are right that the question is unrelated. These are standard Java puzzlers. If you just want to know the answer, google it. I would prefer you to learn something by helping you work it out. When you see 'i' what type do you assume it is? 'int' right? Well its not that type. ;) There are three types for first question. There is two types from the second question.

    Another hint, what are the special values that float and double support and what difference would they make here?

    ReplyDelete
  3. Technically, loading a class in 2 different classloaders really gives you 2 *distinct* classes ; so at the end of the day, there are no "multiple copies" of the static fields of any given class.

    ReplyDelete
  4. @Oliver, You are technically correct. From a coding point of view there is one source class, even though at runtime there are different instances of a Class (with the same name)

    ReplyDelete
  5. One interesting point is that if a reference variable which is static and has null value, it can still call a method or access variable without throwing NPE. e.g.

    private static _instance= null;

    instance.process();// will not throw NPE.

    I have also shared my view as 10 Points on Static in Java let me know how do you find it.

    ReplyDelete
  6. @Javin, That because static methods are bound at compile time and the contents of the reference is not examined. Personally I think its a coding error to write this way because the code is not doing what it appears which makes it confusing.

    A shorter example, ;)

    ((Thread) null).yield();

    ReplyDelete
  7. Great. Thanks Peter for your explanation with code. This tutorial gives me clear idea about the static fields (I thought they live in perm gen).

    ReplyDelete
  8. It is worth noting that Java 8 JVM doesn't have a perm gen.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Great little gem. Thanks.

    ReplyDelete
  11. Tx. FTR if you hit this page looking for a solution for reproducible testing related to static field initialization in unit tests, as I just have, note that apparently e.g. Powermock has annotations such as its @PrepareForTest et al which run each test in a separate classloader - thus "resetting" previously static-ly initialized fields.

    ReplyDelete
  12. Your loading and unloading services is good and very helpful for every working peoples.

    ReplyDelete

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Unusual Java: StackTrace Extends Throwable