Advertisement
Oppenheimer

Singleton pattern

Feb 25th, 2025
2,873
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Singleton{
  4.  
  5.     private static Singleton obj;
  6.  
  7.     private Singleton(){
  8.  
  9.     }
  10.     public static Singleton getSingleton(){
  11.         if(obj == null){
  12.  
  13.             synchronized(Singleton.class){
  14.                 if(obj == null){
  15.                     // in case not already created by another thread
  16.                     obj = new Singleton();
  17.                 }
  18.                
  19.             }
  20.            
  21.         }
  22.         return obj;
  23.     }
  24. }
  25.  
  26.  
  27. /*
  28.  * 1. private constructor so no new object creation
  29.  * 2. obj creation using static method
  30.  * 3. ob ject is static
  31.  *
  32.  * 4. Thread safety -> synchronized block instead of synchronized method
  33.  * to sync only required code
  34.  */
  35.  
  36. public class Main{
  37.     public static void main(String args[]) throws Exception{
  38.         // singleton design pattern -> only one object is used
  39.         Singleton obj1 = Singleton.getSingleton();
  40.         System.out.println(obj1.hashCode());
  41.  
  42.         Singleton obj2 = Singleton.getSingleton();
  43.         System.out.println(obj2.hashCode());
  44.  
  45.         // same hashCode means same object
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement