sys_debug
sys_debug

Reputation: 4003

Java TreeMap single creation

I have this application that requires the creation of TreeMap<>() and this map only requires to be created once. I have the code to create the map and it works. I also have working methods to save and load the map. I was wondering what is the best way to create the map only once behind the scenes and store it before I run the application for the first time and only this once? I don't want to create a button that says "create map" and then never visit that page again. Any ideas?

Thanks,

Upvotes: 1

Views: 663

Answers (2)

solendil
solendil

Reputation: 8458

The following class will instanciate the map during the first call to its get method. You just need to call Bla.getMap() everytime you need the map, without worrying about its initialization.

public class Bla {
    private static TreeMap map = null;
    public static TreeMap getMap() {
        if (map==null) {
            synchronized (Bla.class) {
                map = new TreeMap...
               // rest of initialization code
            }
        }
        return map;
    }
}

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533880

You can declare it in a static field. This will be created only once and if you call load on it in a static block, it is called only once.

e.g.

public static final MyTreeMapWrapper map = new MyTreeMapWrapper();

class MyTreeMapWrapper {
   final TreeMap treeMap = ...

   MyTreeMapWrapper() {
        // loads data into treeMap

Upvotes: 1

Related Questions