-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathConcurrentHashMapImplementation.java
68 lines (59 loc) · 1.63 KB
/
ConcurrentHashMapImplementation.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
/**
* Data-Structures-And-Algorithms-in-Java
* ConcurrentHashMapImplementation.java
*/
package com.deepak.data.structures.Hashing;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* Concurrent HashMap implementation
* @author Deepak
*/
public class ConcurrentHashMapImplementation {
// Map to store orders for different cities
static Map<String, AtomicLong> ordersMap = new ConcurrentHashMap<>();
/**
* Method to process orders
*/
static void processOrders() {
for (String city : ordersMap.keySet()) {
for (int i = 0; i < 50; i++) {
ordersMap.get(city).getAndIncrement();
}
}
}
/**
* Main method to start the flow of program
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
ordersMap.put("Delhi", new AtomicLong());
ordersMap.put("London", new AtomicLong());
ordersMap.put("New York", new AtomicLong());
ordersMap.put("Sydney", new AtomicLong());
// Executor service with 2 threads
ExecutorService service = Executors.newFixedThreadPool(2);
// Submitting two tasks to service
service.submit(new Runnable() {
@Override
public void run() {
processOrders();
}
});
service.submit(new Runnable() {
@Override
public void run() {
processOrders();
}
});
// Waiting for 1 second and then shutting down the service
service.awaitTermination(1, TimeUnit.SECONDS);
service.shutdown();
System.out.println(ordersMap);
}
}