Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Singleton{
- private static Singleton obj;
- private Singleton(){
- }
- public static Singleton getSingleton(){
- if(obj == null){
- synchronized(Singleton.class){
- if(obj == null){
- // in case not already created by another thread
- obj = new Singleton();
- }
- }
- }
- return obj;
- }
- }
- /*
- * 1. private constructor so no new object creation
- * 2. obj creation using static method
- * 3. ob ject is static
- *
- * 4. Thread safety -> synchronized block instead of synchronized method
- * to sync only required code
- */
- public class Main{
- public static void main(String args[]) throws Exception{
- // singleton design pattern -> only one object is used
- Singleton obj1 = Singleton.getSingleton();
- System.out.println(obj1.hashCode());
- Singleton obj2 = Singleton.getSingleton();
- System.out.println(obj2.hashCode());
- // same hashCode means same object
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement