public final class IvoryTower {
private IvoryTower() { }
private static final IvoryTower INSTANCE = new IvoryTower();
public static IvoryTower getInstance() { return INSTANCE; } }
public final class ThreadSafeDoubleCheckLocking {
private static volatile ThreadSafeDoubleCheckLocking instance;
private static boolean flag = true;
private ThreadSafeDoubleCheckLocking() { if (flag) { flag = false; } else { throw new IllegalStateException("Already initialized."); } }
public static ThreadSafeDoubleCheckLocking getInstance() { var result = instance; if (result == null) { synchronized (ThreadSafeDoubleCheckLocking.class) { result = instance; if (result == null) { instance = result = new ThreadSafeDoubleCheckLocking(); } } } return result; } }
public final class ThreadSafeLazyLoadedIvoryTower {
private static ThreadSafeLazyLoadedIvoryTower instance;
private ThreadSafeLazyLoadedIvoryTower() { if (instance == null) { instance = this; } else { throw new IllegalStateException("Already initialized."); } }
public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() { if (instance == null) { instance = new ThreadSafeLazyLoadedIvoryTower(); }
return instance; } }
public enum EnumIvoryTower {
INSTANCE;
@Override public String toString() { return getDeclaringClass().getCanonicalName() + "@" + hashCode(); } }
public final class InitializingOnDemandHolderIdiom {
private InitializingOnDemandHolderIdiom() { }
public static InitializingOnDemandHolderIdiom getInstance() { return HelperHolder.INSTANCE; }
private static class HelperHolder { private static final InitializingOnDemandHolderIdiom INSTANCE = new InitializingOnDemandHolderIdiom(); } }
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
var ivoryTower1 = IvoryTower.getInstance(); var ivoryTower2 = IvoryTower.getInstance(); LOGGER.info("ivoryTower1={}", ivoryTower1); LOGGER.info("ivoryTower2={}", ivoryTower2);
var threadSafeIvoryTower1 = ThreadSafeLazyLoadedIvoryTower.getInstance(); var threadSafeIvoryTower2 = ThreadSafeLazyLoadedIvoryTower.getInstance(); LOGGER.info("threadSafeIvoryTower1={}", threadSafeIvoryTower1); LOGGER.info("threadSafeIvoryTower2={}", threadSafeIvoryTower2);
var enumIvoryTower1 = EnumIvoryTower.INSTANCE; var enumIvoryTower2 = EnumIvoryTower.INSTANCE; LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); LOGGER.info("enumIvoryTower2={}", enumIvoryTower2);
var dcl1 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl1.toString()); var dcl2 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl2.toString());
var demandHolderIdiom = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom.toString()); var demandHolderIdiom2 = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom2.toString()); } }
|