Java Language Concurrent Collections Thread-safe Collections

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

By default, the various Collection types are not thread-safe.

However, it's fairly easy to make a collection thread-safe.

List<String> threadSafeList = Collections.synchronizedList(new ArrayList<String>());
Set<String> threadSafeSet = Collections.synchronizedSet(new HashSet<String>());
Map<String, String> threadSafeMap = Collections.synchronizedMap(new HashMap<String, String>());

When you make a thread-safe collection, you should never access it through the original collection, only through the thread-safe wrapper.

Java SE 5

Starting in Java 5, java.util.collections has several new thread-safe collections that don't need the various Collections.synchronized methods.

List<String> threadSafeList = new CopyOnWriteArrayList<String>();
Set<String> threadSafeSet = new ConcurrentHashSet<String>();
Map<String, String> threadSafeMap = new ConcurrentHashMap<String, String>();


Got any Java Language Question?