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:
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


× 3 = six



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books