What Are Concurrent Collections in Java?

What Are Concurrent Collections in Java? Explained with Code Examples

Java provides a set of thread-safe collection classes under the java.util.concurrent package, known as concurrent collections. These collections are optimized for multi-threaded environments, offering better performance and safety compared to synchronized collections.

Why Use Concurrent Collections?

  • They provide high-performance thread-safe operations.
  • They use fine-grained locking or non-blocking algorithms to enhance efficiency.
  • They avoid synchronization overhead in multi-threaded applications.

Key Concurrent Collections

1. ConcurrentHashMap

Unlike HashMap, which is not thread-safe, and Hashtable, which synchronizes all methods, ConcurrentHashMap allows concurrent updates without locking the entire map.

import java.util.concurrent.*;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        ConcurrentHashMap map = new ConcurrentHashMap<>();
        map.put(1, "Java");
        map.put(2, "Python");
        map.put(3, "C++");

        System.out.println("Value for key 1: " + map.get(1));
    }
}

2. CopyOnWriteArrayList

This is a thread-safe version of ArrayList, where modifications create a new copy of the list to avoid ConcurrentModificationException.

import java.util.concurrent.*;

public class CopyOnWriteArrayListExample {
    public static void main(String[] args) {
        CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();
        list.add("Java");
        list.add("Spring");
        list.add("Hibernate");

        for (String item : list) {
            System.out.println(item);
        }
    }
}

3. BlockingQueue

BlockingQueue implementations like ArrayBlockingQueue and LinkedBlockingQueue are useful for producer-consumer patterns.

import java.util.concurrent.*;

public class BlockingQueueExample {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue queue = new LinkedBlockingQueue<>(2);
        queue.put("Task1");
        queue.put("Task2");
        System.out.println(queue.take());
    }
}

4. ConcurrentLinkedQueue

This is a non-blocking, thread-safe queue based on a lock-free linked node algorithm.

import java.util.concurrent.*;

public class ConcurrentLinkedQueueExample {
    public static void main(String[] args) {
        ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>();
        queue.add("Java");
        queue.add("Kotlin");
        System.out.println(queue.poll());
    }
}

Conclusion

Concurrent collections are essential for writing high-performance, thread-safe Java applications. They provide better efficiency compared to traditional synchronized collections.

Please follow and like us:

Leave a Comment