001package singleton.classloading; 002 003/** 004 * This example shows that you need to be careful to ensure that 005 * singletons are not accessed before they are created! 006 */ 007class S { 008 private static S instance; 009 public static int numInstances; 010 public static S getInstance() { 011 if (instance == null) { 012 instance = new S(); 013 } 014 return instance; 015 } 016 017 private S() { 018 S.numInstances++; 019 B.doNothing(); // B is loaded here, during A's constructor 020 } 021} 022 023class B { 024 // B caches the only instance of S 025 public static S a = S.getInstance(); 026 public static void doNothing() {} 027} 028 029class Main { 030 public static void main(String[] args) { 031 System.out.println(S.getInstance() == B.a); // false! 032 System.out.println(S.numInstances); // 2! 033 } 034}