
In my SCJD assignment, I had to decide how to meet a requirement which was that the meta information of the database should be read only once and reused them on later uses.
For example, in starting up time, the application will read the header information of the database such as the size of the database record, the number of fields, or the length of each field.
and those header information will decide how the data is organized and should be treated when read and write operation. And those header information won't change during the run-time operation which means they are static in the single session.
In java programming language, you could achieve this by several choices explained in the following.
Singleton
pros
- Global access point(exactly one instance exists in one JVM)
- Cuts the starting up time and memory allocation(Singleton object is instantiated only when the instance is needed(if lazy instantiation is applied))
cons
- can't be inherited(because the constractor of the singleton class should be private)
----memo---
1) If the lazy initialization is applied, A Singleton ojbect is initialized at the time when the getInstance method is invoked at first.
2) If the eager initialization is applied, the Singleton object is initialized by a static initializer and in other words, the Singleton object is created before any thread accesses the static Singleton object.
What's the difference b/w 2 cases??!!
--->answer is When JVM loads the singleton class into the memory, the eager initialization applied Singleton class is instantiated, but not for the lazy initialization applied one.
When JVM loads the particular class is at the time of the first occurence of any one of the following.
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.
-------------
References:
No comments:
Post a Comment