|
| 1 | +package src.test.java.com.designpatterns.singletonpattern; |
| 2 | + |
| 3 | +import org.junit.Assert; |
| 4 | +import org.junit.Test; |
| 5 | +import src.main.java.com.designpatterns.singletonpattern.Singleton; |
| 6 | + |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.concurrent.ExecutorService; |
| 9 | +import java.util.concurrent.Executors; |
| 10 | +import java.util.concurrent.TimeUnit; |
| 11 | + |
| 12 | +public class SingletonTest { |
| 13 | + private static volatile ArrayList<Integer> hashCodeList = new ArrayList<>(); |
| 14 | + |
| 15 | + @Test |
| 16 | + public void testSingleton() throws InterruptedException { |
| 17 | + boolean testFailed = false; |
| 18 | + ExecutorService es = Executors.newCachedThreadPool(); |
| 19 | + // Creates 15 threads and makes all of them access the Singleton class |
| 20 | + // Saves the hash code of the object in a static list |
| 21 | + for (int i = 0; i < 15; i++) |
| 22 | + es.execute(() -> { |
| 23 | + try { |
| 24 | + Singleton singletonInstance = Singleton.getInstance(); |
| 25 | + int singletonInsCode = singletonInstance.hashCode(); |
| 26 | + System.out.println(singletonInsCode); |
| 27 | + hashCodeList.add(singletonInsCode); |
| 28 | + } catch (Exception e) { |
| 29 | + System.out.println("Exception is caught"); |
| 30 | + } |
| 31 | + }); |
| 32 | + es.shutdown(); |
| 33 | + boolean finished = es.awaitTermination(1, TimeUnit.MINUTES); |
| 34 | + // wait for all threads to finish |
| 35 | + if (finished) { |
| 36 | + Integer firstCode = hashCodeList.get(0); |
| 37 | + for (Integer code : hashCodeList) { |
| 38 | + if (!firstCode.equals(code)) { |
| 39 | + testFailed = true; |
| 40 | + } |
| 41 | + } |
| 42 | + Assert.assertFalse(testFailed); |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments