Concurrent Collections and Parallel Streams in Java

Master concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList), parallel streams, and parallel processing considerations for the OCP 21 exam.

Table of Contents

1. Concurrent Collections

Concurrent collections are thread-safe collections designed for use in multi-threaded environments without external synchronization.

1.1 Common Concurrent Collections

  • ConcurrentHashMap - Thread-safe HashMap
  • CopyOnWriteArrayList - Thread-safe ArrayList
  • CopyOnWriteArraySet - Thread-safe Set
  • BlockingQueue - Thread-safe queue with blocking operations
  • ConcurrentLinkedQueue - Thread-safe queue

2. ConcurrentHashMap

ConcurrentHashMap is a thread-safe implementation of Map that allows concurrent reads and writes.

2.1 Basic Operations

Example:
import java.util.concurrent.ConcurrentHashMap;

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

// Thread-safe operations
map.put("key1", 1);
map.putIfAbsent("key2", 2);
map.replace("key1", 1, 10);
map.remove("key2", 2);

// Atomic operations
map.compute("key1", (k, v) -> v == null ? 1 : v + 1);
map.computeIfAbsent("key3", k -> 3);
map.computeIfPresent("key1", (k, v) -> v * 2);
map.merge("key1", 5, (oldVal, newVal) -> oldVal + newVal);

3. CopyOnWriteArrayList

CopyOnWriteArrayList creates a new copy of the array on each modification, making it thread-safe for read-heavy operations.

3.1 Usage

Example:
import java.util.concurrent.CopyOnWriteArrayList;

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

list.add("Item1");
list.add("Item2");

// Iteration is safe even during modification
for (String item : list) {
    System.out.println(item);  // Safe - uses snapshot
    list.add("NewItem");  // Modification creates new copy
}

// Best for read-heavy, write-light scenarios

4. Blocking Queues

BlockingQueue provides thread-safe queue operations that block when the queue is full or empty.

4.1 Common Implementations

Example:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

// Bounded queue
BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

// Producer
queue.put("Item");  // Blocks if queue is full
queue.offer("Item", 1, TimeUnit.SECONDS);  // Timeout

// Consumer
String item = queue.take();  // Blocks if queue is empty
String item2 = queue.poll(1, TimeUnit.SECONDS);  // Timeout

// Unbounded queue
BlockingQueue<String> unbounded = new LinkedBlockingQueue<>();

5. Parallel Streams

Parallel streams enable parallel processing of stream operations using multiple threads.

5.1 Creating Parallel Streams

Example:
List<Integer> numbers = IntStream.range(1, 1000000).boxed().collect(Collectors.toList());

// Create parallel stream
Stream<Integer> parallel = numbers.parallelStream();

// Convert sequential to parallel
Stream<Integer> parallel2 = numbers.stream().parallel();

// Parallel processing
long sum = numbers.parallelStream()
    .mapToInt(Integer::intValue)
    .sum();

// forEachOrdered maintains order
numbers.parallelStream()
    .forEachOrdered(System.out::println);

5.2 Parallel Stream Considerations

Important: Parallel streams require:
  • Stateless operations
  • Non-interfering operations
  • Associative reduction operations
  • Sufficient data size to justify overhead

6. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • ConcurrentHashMap: Thread-safe Map, allows concurrent reads/writes
  • compute(): Atomic compute operation
  • merge(): Atomic merge operation
  • CopyOnWriteArrayList: Thread-safe List, creates copy on write
  • CopyOnWriteArraySet: Thread-safe Set based on CopyOnWriteArrayList
  • BlockingQueue: Thread-safe queue with blocking operations
  • put()/take(): Blocking operations on BlockingQueue
  • offer()/poll(): Non-blocking operations with timeout
  • parallelStream(): Create parallel stream from collection
  • parallel(): Convert sequential stream to parallel
  • forEachOrdered(): Maintains order in parallel streams
  • Parallel Requirements: Stateless, non-interfering, associative operations

Post a Comment

0 Comments