Advertisement
Josif_tepe

Untitled

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