Concurrent Collections

Concurrent collections are designed for use in multithreaded environments. This tutorial will teach you how to use concurrent collections in Java.

Using ConcurrentHashMap

The ConcurrentHashMap class is a thread-safe version of HashMap:


import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executor.execute(() -> {
                map.put(Thread.currentThread().getName(), finalI);
                System.out.println(map);
            });
        }
        executor.shutdown();
    }
}
      

Using CopyOnWriteArrayList

The CopyOnWriteArrayList class is a thread-safe version of ArrayList:


import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        List list = new CopyOnWriteArrayList<>();
        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executor.execute(() -> {
                list.add(Thread.currentThread().getName() + " - " + finalI);
                System.out.println(list);
            });
        }
        executor.shutdown();
    }
}
      

In this example, CopyOnWriteArrayList is used to store elements in a thread-safe way.

Continue exploring our intermediate tutorials to learn more about Java programming.

Scroll to Top