Здравствуйте!
Как в java правильно сделать lazy initialization?
Сначала было сделано так:
public class ServicesFactory {
private static ServicesFactory instance = null;
private static ImagesService imagesService = null;
public static synchronized ServicesFactory getInstance() {
if (instance == null) {
instance = new ServicesFactory();
}
return instance;
}
public ImagesService getImagesService() {
if (imagesService == null) {
imagesService = new DefImagesServiceImpl();
}
return imagesService;
}
}
Сделал так:
public class ServicesFactory {
private static ServicesFactory instance = null;
private static ImagesService imagesService = null;
public static synchronized ServicesFactory getInstance() {
if (instance == null) {
instance = new ServicesFactory();
}
return instance;
}
public synchronized ImagesService getImagesService() {
if (imagesService == null) {
imagesService = new DefImagesServiceImpl();
}
return imagesService;
}
}
Но, по ссылке http://en.wikipedia.org/wiki/Double-checked_locking написано:
// Correct lazy initialization in Java
// This relies on the fact that inner classes are not loaded until they are referenced.
@ThreadSafe
class Foo {
private static class HelperHolder {
public static Helper helper = new Helper();
}
public static Helper getHelper() {
return HelperHolder.helper;
}
}