fork download
  1. //Thread-safe Singleton class with synchronized getInstance()
  2. class singleton{
  3. private static singleton instance;
  4. private singleton(){
  5. System.out.println("An instance is created");
  6. }
  7. public static synchronized singleton getInstance(){
  8. if(instance == null)
  9. {
  10. instance=new singleton();
  11. }
  12. return instance;
  13. }
  14. void method()
  15. {
  16. System.out.println("successfully executed!");
  17. }
  18. }
  19.  
  20. public class Main{
  21. public static void main(String[] args)
  22. {
  23. singleton obj1 = singleton.getInstance();
  24. singleton obj2 = singleton.getInstance();
  25.  
  26. obj1.method();
  27.  
  28. if(obj1 == obj2)
  29. {
  30. System.out.println("Whatever!");
  31. }
  32. else{
  33. System.out.println("porashuna koro toh? porte hobe! nokol ar hobe na!");
  34. }
  35. }
  36. }
Success #stdin #stdout 0.07s 52468KB
stdin
Standard input is empty
stdout
An instance is created
successfully executed!
Whatever!