-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyValueStoreTest.java
97 lines (88 loc) · 2.65 KB
/
KeyValueStoreTest.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import server.IServer;
import server.Server;
/**
* This is a Junit test class for the RMI server.
*/
public class KeyValueStoreTest {
private IServer obj;
/**
* Instantiates and run the RMI server at port 1099.
*/
@BeforeEach
void setUp() {
try {
this.obj = new Server(1099);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
/**
* Tests the thread safety of the RMI server by using 100 threads to manipulate the hashmap.
*
* @throws InterruptedException the interrupted exception
*/
@Test
public void testThreadSafety() throws InterruptedException {
int numThreads = 100;
CountDownLatch addLatch = new CountDownLatch(numThreads / 2);
CountDownLatch deleteLatch = new CountDownLatch(numThreads / 2);
AtomicInteger adds = new AtomicInteger(0);
AtomicInteger deletes = new AtomicInteger(0);
Runnable addTask = () -> {
try {
obj.put("key" + adds.incrementAndGet(), "value");
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
addLatch.countDown(); // start the add operations countdown
}
};
Runnable deleteTask = () -> {
try {
addLatch.await(); // wait for the add operations to finish
obj.delete("key" + deletes.incrementAndGet());
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
deleteLatch.countDown(); // start the delete operations countdown
}
};
for (int i = 0; i < numThreads; i++) { // spun the threads
if (i % 2 == 0) {
new Thread(addTask).start();
} else {
new Thread(deleteTask).start();
}
}
deleteLatch.await(); // wait for the delete operations to finish
try {
int expectedSize = adds.get() - deletes.get(); // compute the expected hashmap size
int actualSize = obj.getMapSize(); // get the actual hashmap size
assertEquals(expectedSize, actualSize); // compare the two values
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
/**
* Shuts the RMI server down gracefully.
*/
@AfterEach
void tearDown() {
try {
obj.shutdown();
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}