// ConcurrentHashMap usage and thread-safe operations
ConcurrentHashMap map = new ConcurrentHashMap<>();
// Atomic put if absent
map.putIfAbsent("key", 42);
// Atomic compute operations
map.compute("key", (k, v) -> (v == null) ? 1 : v + 1);
// Thread-safe iteration
map.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
// Atomic get or default
int value = map.getOrDefault("nonexistent", 0);
// CopyOnWriteArrayList thread-safe operations
CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();
// Thread-safe addition
list.add("First Item");
// Safe iteration while modifying
for (String item : list) {
if (item.equals("First Item")) {
list.remove(item);
list.add("Modified Item");
}
}
// Atomic operations
list.addIfAbsent("Unique Item");
// BlockingQueue thread-safe operations
BlockingQueue queue = new LinkedBlockingQueue<>(10);
// Producer thread
new Thread(() -> {
try {
for (int i = 0; i < 100; i++) {
// Blocks if queue is full
queue.put(i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
// Consumer thread
new Thread(() -> {
try {
while (true) {
// Blocks if queue is empty
Integer item = queue.take();
processItem(item);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();