fork download
  1. //// Thread-safe Singleton with Double-Checked Locking
  2. class singleton{
  3. private static volatile singleton instance;
  4. private singleton(){
  5. System.out.println("singleton instance is created");
  6. }
  7. public static singleton getInstance(){
  8. if(instance==null)
  9. {
  10. synchronized(singleton.class){
  11. if(instance==null)
  12. {
  13. instance = new singleton();
  14. }
  15. }
  16. }
  17. return instance;
  18. }
  19. void method()
  20. {
  21. System.out.println("Hello from Singleton!");
  22. }
  23. }
  24.  
  25. public class Main{
  26. public static void main(String[] args)
  27. {
  28. singleton obj1 = singleton.getInstance();
  29. singleton obj2 = singleton.getInstance();
  30.  
  31. obj1.method();
  32.  
  33. if(obj1==obj2)
  34. {
  35. System.out.println("Both references point to the same instance!");
  36. }
  37. }
  38. }
Success #stdin #stdout 0.07s 54524KB
stdin
Standard input is empty
stdout
singleton instance is created
Hello from Singleton!
Both references point to the same instance!