9

Make an instance of the Singleton Class object eligible for GC

 3 years ago
source link: https://www.codesd.com/item/make-an-instance-of-the-singleton-class-object-eligible-for-gc.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Make an instance of the Singleton Class object eligible for GC

advertisements

I have a class JAXBReader which hold unmarshalled xml file using the jaxb generated classes. I have used the singleton design so that I need not unmarshall the file again and again. The object of this class (precisely the unmarshalled xml) is needed only to initialize an enum having eight constants. The constructor of enum constants use the singleton object to get their required part of the xml.

After the enum is initialized, I don't need the objetc of JAXBReader in my system. How can I achieve this?

I read here that I can call a setter to assign null to the static singelton instance but I don't want to do it externally. I want that, the instance is assigned null automatically after the enum is initialized.

I am using Java 1.7


One option would be to do all of this within the static initializers of the enum. Keep a static field within the enum itself, write a private static method to get the contents of the file, reading it if necessary, and then at the end of the enum initialization - in a static initializer block - set it to null:

public enum Foo {
    VALUE1, VALUE2, VALUE3;
    private static JAXBReader singleReader;

    static {
        singleReader = null; // Don't need it any more
    }

    private Foo() {
        JAXBReader reader = getReader();
        // Use the reader
    }

    private static JAXBReader getReader() {
        // We don't need to worry about thread safety, as all of this
        // will be done in a single thread initializing the enum
        if (singleReader == null) {
            // This will only happen once
            singleReader = new JAXBReader(...);
        }
        return singleReader;
    }
}

This way only the enum knows that the reader is a singleton - you can still create a new JAXBReader whenever you like externally, which could be very useful for testing.

(I'm somewhat nervous about enum initialization needing an external resource to start with, but I can see that it may be hard to avoid.)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK