fork download
  1. import java.util.function.Supplier;
  2.  
  3. class Ideone {
  4. public static void main (String[] args) {
  5. Singleton.setSingletonFactory(SubSingleton.SUB_SINGLETON_FACTORY);
  6. Singleton instanceOne = Singleton.getInstance();
  7. Singleton instanceTwo = Singleton.getInstance();
  8.  
  9. System.out.println(instanceOne == instanceTwo);
  10.  
  11. try {
  12. SubSingleton.SUB_SINGLETON_FACTORY.get();
  13. } catch (IllegalStateException e) {
  14. System.out.println("Rightfully thrown " + e);
  15. }
  16. }
  17. }
  18.  
  19. class Singleton {
  20. private static volatile Singleton INSTANCE = null;
  21.  
  22. private static Supplier<? extends Singleton> factory;
  23.  
  24. public static void setSingletonFactory(Supplier<? extends Singleton> factory) {
  25. Singleton.factory = factory;
  26. }
  27.  
  28. public static Singleton getInstance() {
  29. if (INSTANCE == null) {
  30. synchronized (Singleton.class) {
  31. if (INSTANCE == null) {
  32. INSTANCE = factory.get();
  33. }
  34. }
  35. }
  36. return INSTANCE;
  37. }
  38.  
  39. protected Singleton() {
  40. if (INSTANCE == null) {
  41. synchronized (Singleton.class) {
  42. if (INSTANCE == null) {
  43. // Set attribute of Singleton as necessary
  44. } else {
  45. throw cannotReinitializeSingletonIllegalStateException();
  46. }
  47. }
  48. } else {
  49. throw cannotReinitializeSingletonIllegalStateException();
  50. }
  51. }
  52.  
  53. private static IllegalStateException cannotReinitializeSingletonIllegalStateException() {
  54. return new IllegalStateException("Cannot reinitialize Singleton");
  55. }
  56. }
  57.  
  58. class SubSingleton extends Singleton {
  59. public static final Supplier<SubSingleton> SUB_SINGLETON_FACTORY = SubSingleton::new;
  60.  
  61. private SubSingleton() {}
  62. }
Success #stdin #stdout 0.11s 36092KB
stdin
Standard input is empty
stdout
true
Rightfully thrown java.lang.IllegalStateException: Cannot reinitialize Singleton