Question

I have singleton A.class. Runnable loadTask may be evoked or not, that's why I'm thinking about lazy initialization. I'm concerned about memory usage. So the question is Does lazy initialization worthy to be implemented? Or memory for function body consumes little more then memory for instant initialization and easier to ignore memory consumption difference.

I understand that the definition of the function MUST consumes memory somewhere.

P.S. I understand that memory for function body is not allocated in Heap.

P.S. Instrumentation.class, sizeOf, Runtime.freeMemory() works with class fields/attributes only.

class A_LazyInit {
    Runnable loadTask;
    void load() {
        if(loadTask == null) loadTask = new Runnable() {
            public void run() {
                loadFileFromInternet();
            }
        };
        new Thread(loadTask).start();
    }
    void useMethod() {
        if(isGoodCondition()) load();
    }
}

vs

class A {
    Runnable loadTask = new Runnable() {
        public void run() {
            loadFileFromInternet();
        }
    };
    void useMethod() {
        if(isGoodCondition()) new Thread(loadTask).start();
    }
}

No correct solution

OTHER TIPS

You won't be saving any memory with lazy initialization here. The memory for the code will be reserved whether or not you initialize it eagerly (it's allocated when the class is loaded).

Since initializing your loadTask variable won't take long, using lazy initialization doesn't give you an advantage here in any case.

I would make use of the fact that classes are lazily initialized already.

You could just doing this

enum Singleton {
     INSTANCE;

     Singleton() {
         loadFileFormTheInternet();
     }
}

This is thread safe and lazy loaded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top