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