Most common said is to avoid lazy initialization if not required.
Lazy initialization play an important while performance is key.
As mentioned in effective java, there are two ways to do better lazy initialization.
In simple word, avoid synchronization on whole getter method, instead of that first check for null or default value(In case of primitives) and if required initialization then only use synchronization.
Following example depict simple use of double checked lock
Lazy Initialization holder class Idiom (For static field)
It is also called as initialization on demand holder class idiom.
It guarantee that a class will not be initialized until it used(JLS 12.4.1).
Following code depict the same:-
Lazy initialization play an important while performance is key.
As mentioned in effective java, there are two ways to do better lazy initialization.
- Double checked Lock (For Instance Field)
- Lazy Initialization holder class Idiom (For static field)
In simple word, avoid synchronization on whole getter method, instead of that first check for null or default value(In case of primitives) and if required initialization then only use synchronization.
Following example depict simple use of double checked lock
private volatile FiledType filed;
FiledType getFiledType() {
FiledType result = filed; //Use at least once pre Initialized
if (result == null) { // First check (No locking)
synchronized(this) {
if (result == null) { //Second checking (With locking)
result = filed = computeFieldValue();
}
}
}
return result;
} Lazy Initialization holder class Idiom (For static field)
It is also called as initialization on demand holder class idiom.
It guarantee that a class will not be initialized until it used(JLS 12.4.1).
Following code depict the same:-
//Lazy initialization holder class idiom for static filed initialization
private static class FiledHolder {
static final FiledType filed = computeFieldValue();
}
FiledType getFiledType() {
return FiledHolder.filed; //Here class is initialized
}
No comments:
Post a Comment