Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. package mk.ukim.finki.os.lab3;
  2.  
  3. import java.util.HashSet;
  4. import java.util.concurrent.Semaphore;
  5.  
  6. public class Singleton {
  7.     static int initCounter = 0;
  8.  
  9.     private static volatile Singleton singleton;
  10.     private static Semaphore initalPresence = new Semaphore(1);
  11.  
  12.     private Singleton() {
  13.         // initialize empty
  14.     }
  15.  
  16.     public static Singleton getInstance() {
  17.         if (initalPresence.tryAcquire()) {
  18.             singleton = new Singleton();
  19.             synchronized (Singleton.class) {
  20.                 initCounter += 1;
  21.             }
  22.         }
  23.         System.out.println(String.format("Instance (%s)", System.identityHashCode(singleton)));
  24.         return singleton;
  25.     }
  26.  
  27.  
  28.     public static void main(String[] args) throws InterruptedException {
  29.         final int NUM_TESTS = 1000; // number of test cases
  30.         final int NUM_THREADS = 100; // threads per test case
  31.         for (int testCase = 0; testCase < NUM_TESTS; testCase++) {
  32.             HashSet<Thread> threadHashSet = new HashSet<>();
  33.  
  34.             for (int i = 0; i < NUM_THREADS; i++) {
  35.                 Thread thread = new Thread(Singleton::getInstance);
  36.                 threadHashSet.add(thread);
  37.             }
  38.  
  39.             for (Thread t : threadHashSet) {
  40.                 t.start();
  41.             }
  42.             for (Thread t : threadHashSet) {
  43.                 t.join();
  44.             }
  45.  
  46.             if (initCounter == 1) {
  47.                 System.out.println(String.format("Test case: %d passed!", testCase));
  48.             } else {
  49.                 System.err.println(String.format("Test case: %d failed to synchronize!", testCase));
  50.             }
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement