Advertisement
Josif_tepe

Untitled

Apr 4th, 2021
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.concurrent.Semaphore;
  3.  
  4. public class Singleton {
  5.  
  6.     private static volatile Singleton singleton;
  7.     static Semaphore semaphore;
  8.  
  9.     private Singleton() { semaphore = new Semaphore(1); }
  10.  
  11.     public  Singleton getInstance() throws InterruptedException{
  12.         // TODO: 3/29/20 Synchronize this
  13.         semaphore.acquire();
  14.         if(singleton == null) {
  15.             System.out.println("created singleton");
  16.             singleton = new Singleton();
  17.         }
  18.         semaphore.release();
  19.         return singleton;
  20.     }
  21.  
  22.     public static void main(String[] args) {
  23.         // TODO: 3/29/20 Simulate the scenario when multiple threads call the method getInstance
  24.         List<Thread> list = new ArrayList<>();
  25.         Singleton s = new Singleton();
  26.         for(int i = 0; i < 20; i++) {
  27.             list.add(new Thread(new Runnable() {
  28.                 @Override
  29.                 public void run() {
  30.                     try {
  31.                         s.getInstance();
  32.                     }
  33.                     catch (InterruptedException e) {
  34.                        
  35.                     }
  36.                 }
  37.             }));
  38.         }
  39.         for(int i = 0; i < 20; i++) {
  40.             list.get(i).start();
  41.         }
  42.         for(int i = 0; i < 20; i++) {
  43.             try {
  44.                 list.get(i).join();
  45.             }
  46.             catch (InterruptedException e) {
  47.                 System.out.println(e);
  48.             }
  49.         }
  50.  
  51.     }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement