-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConcurrentRW.java
More file actions
79 lines (59 loc) · 2.01 KB
/
ConcurrentRW.java
File metadata and controls
79 lines (59 loc) · 2.01 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
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
import java.util.*;
import java.nio.charset.Charset;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentRW {
private static Random rand = new Random();
public static String randomString() {
byte[] array = new byte[10];
rand.nextBytes(array);
String randomString = new String(array, Charset.forName("ASCII"));
return randomString;
}
public static int randomBoundedInt() {
return rand.nextInt(10001);
}
static class DataRW implements Runnable {
Map<Integer, String> map;
DataRW(ConcurrentHashMap<Integer, String> map) {
this.map = map;
}
public void run() {
for (int i = 0; i < 1000; i++) {
int idx = ConcurrentRW.randomBoundedInt();
String item = ConcurrentRW.randomString();
map.put(idx, item);
System.out.printf("%d: %s\n", idx, item);
}
}
}
public static void main(String[] args) {
int numThreads = 1;
if (args.length == 0) {
System.err.println("Usage: java ConcurrentRW [num of threads]");
System.exit(1);
} else {
try {
numThreads = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Usage: java ConcurrentRW [num of threads]");
System.exit(1);
}
}
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
List<Thread> threadPool = new ArrayList<>();
for (int i = 0; i < numThreads; i++) {
DataRW rw = new DataRW(map);
threadPool.add(new Thread(rw));
}
for (Thread t : threadPool) {
t.start();
}
for (Thread t : threadPool) {
try {
t.join();
} catch (InterruptedException e) {
System.err.println("Error encountered when trying to join");
}
}
}
}