Giriş
Lazy singleton olaran adlandırabiliriz. Açıklaması şöyle.
Holder içinde Holder ilklendirildiği tuhaf durumlar da gördüm.
Örnek
Şöyle yaparız.
Şöyle yaparız. Yine static alan kullanılıyor tek farkı içte ayrı bir sınıf kullanılması
Lazy singleton olaran adlandırabiliriz. Açıklaması şöyle.
The implementation of the idiom relies on the initialization phase of execution within the Java Virtual Machine (JVM) as specified by the Java Language Specification (JLS).[3] When the class Something is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition LazyHolder within it is not initialized until the JVM determines that LazyHolder must be executed. The static class LazyHolder is only executed when the static method getInstance is invoked on the class Something, and the first time this happens the JVM will load and initialize the LazyHolder class. The initialization of the LazyHolder class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class Something. Since the class initialization phase is guaranteed by the JLS to be sequential, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization. And since the initialization phase writes the static variable INSTANCE in a sequential operation, all subsequent concurrent invocations of the getInstance will return the same correctly initialized INSTANCE without incurring any additional synchronization overhead.Holder sınıfı private static olur ve içinde kendi sınıfımın public static bir alanını içerir.
While the implementation is an efficient thread-safe "singleton" cache without synchronization overhead, and better performing than uncontended synchronization,[4] the idiom can only be used when the construction of Something can be guaranteed to not fail. In most JVM implementations, if construction of Something fails, subsequent attempts to initialize it from the same class-loader will result in a NoClassDefFoundError failure.
Holder içinde Holder ilklendirildiği tuhaf durumlar da gördüm.
Örnek
Şöyle yaparız.
public static class Singleton {
private static class InstanceHolder {
public static Singleton instance = new Singleton();
}
private Singleton(){}
public static Singleton getInstance() {
return InstanceHolder.instance;
}
}
ÖrnekŞöyle yaparız. Yine static alan kullanılıyor tek farkı içte ayrı bir sınıf kullanılması
public class Singleton {
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
private Singleton() {
//...
}
}
Hiç yorum yok:
Yorum Gönder