forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingletonTest.java
More file actions
43 lines (39 loc) · 1.52 KB
/
SingletonTest.java
File metadata and controls
43 lines (39 loc) · 1.52 KB
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
package com.designpatterns.creational.singleton;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class SingletonTest {
private static volatile ArrayList<Integer> hashCodeList = new ArrayList<>();
@Test
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;
}
}
Assertions.assertFalse(testFailed);
}
}
}