Home » Java » Core Java » Java Secret: Loading and unloading static fields

About Peter Lawrey

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 our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*


seven − 7 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close