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

Reference: Java Secret: Loading and unloading static fields from our JCG partner Peter Lawrey at the Vanilla Java.

Related Articles:

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


9 − = five



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close