-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
63 lines (52 loc) · 1.94 KB
/
Main.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
package tech.sharply.experimental.single_threaded_write;
import tech.sharply.experimental.single_threaded_write.data.ThreadSafeList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static tech.sharply.experimental.single_threaded_write.tracking.ThreadTracker.getThreadInfo;
public class Main {
public static void main(String[] args) throws InterruptedException {
final var list = new ThreadSafeList();
final var executor = Executors.newFixedThreadPool(4);
// add multiple entries from different threads
final var addIterations = 50;
final var addCountdown = new CountDownLatch(addIterations);
for (var i = 0; i < addIterations; i++) {
var finalI = i;
executor.submit(() -> {
try {
list.add(finalI).get();
} catch (Exception e) {
e.printStackTrace();
}
addCountdown.countDown();
System.out.println("Executed add iteration: " + finalI + " on " + getThreadInfo());
});
}
addCountdown.await();
// remove multiple entries from different threads
final var removeIterations = 25;
final var toRemove = list.getData().stream().limit(removeIterations).collect(Collectors.toList());
final var removeCountdown = new CountDownLatch(removeIterations);
var i = new AtomicInteger(0);
for (final var el : toRemove) {
executor.submit(() -> {
// remove the i-th element
try {
list.remove(el).get();
} catch (Exception e) {
e.printStackTrace();
}
removeCountdown.countDown();
System.out.println("Executed remove iteration: " + i.getAndIncrement() + " on " + getThreadInfo());
});
}
removeCountdown.await();
// Both executors must be shutdown, otherwise the program will not finish execution
executor.shutdown();
list.shutdown();
System.out.println(list.getThreadTracker().getThreadsDescription());
System.out.println("Execution finished!");
}
}