import
java.util.concurrent.*;
import
java.util.concurrent.locks.*;
public
class
ConcurrentMapWithTreeMapExample {
private
final
ConcurrentSkipListMap<String, Integer>
concurrentMap =
new
ConcurrentSkipListMap<>();
private
final
ExecutorService executorService
= Executors.newFixedThreadPool(
2
);
public
void
addToMap(String key,
int
value)
{
CompletableFuture.runAsync(() -> {
addEntryToMap(key, value);
}, executorService);
}
public
int
getFromMap(String key)
{
return
concurrentMap.getOrDefault(key, -
1
);
}
public
ConcurrentSkipListMap<String, Integer> getOrderedMap()
{
return
new
ConcurrentSkipListMap<>(concurrentMap);
}
private
void
addEntryToMap(String key,
int
value)
{
concurrentMap.put(key, value);
System.out.println(
"Added: "
+ key +
", "
+ value);
}
public
static
void
main(String[] args)
{
ConcurrentMapWithTreeMapExample example
=
new
ConcurrentMapWithTreeMapExample();
CompletableFuture<Void> futureA
= CompletableFuture.runAsync(()
-> example.addToMap(
"A"
,
1
),
example.executorService);
CompletableFuture<Void> futureB
= CompletableFuture.runAsync(()
-> example.addToMap(
"B"
,
2
),
example.executorService);
CompletableFuture.allOf(futureA, futureB).join();
System.out.println(
"Value for A: "
+ example.getFromMap(
"A"
));
System.out.println(
"Value for B: "
+ example.getFromMap(
"B"
));
ConcurrentSkipListMap<String, Integer> orderedMap
= example.getOrderedMap();
System.out.println(
"Ordered Map: "
+ orderedMap);
try
{
example.executorService.shutdown();
}
finally
{
}
}
}