Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making/Allowing single execution of method, in Java

Tags:

java

I have a class with two methods load() and getValue(). The load function loads a set of key value pairs from a file onto a hashMap and the getValue(Object key) method is used to extract values for keys passed to it.

My problem is that I want to create an Object of the class such that load() should be executed only once (to load values into memory) and thereafter the getValue() method should be able to work on this data, each time its called.

What is the best approach to solve this problem? I am quite new to Java and OOP, so please feel free to modify either the question or the title to make it more clear.

like image 256
Amal Antony Avatar asked Dec 07 '22 15:12

Amal Antony


1 Answers

You can use a static initializer block for your class. This is executed only once for a class.

http://www.glenmccl.com/tip_003.htm

like image 67
tom Avatar answered Dec 09 '22 05:12

tom