Standard Java collections are not thread-safe

As I worked for years now in different projects I experienced that many Java programmers think it’s enough to synchronize methods modifying the state of a Collection (put, add, remove, …).I guess they think that an access method (like get) is not affected.

This is a common mistake! If you have concurrent modifying access to collections you have either to synchronize all methods accessing the collection or to use a collection which is designed for this purpose (see java.util.concurrent or Collections.synchronized… if you are using a JDK version < 5).

A small example to illustrate this:

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class StandardCollectionsAreNOTThreadSafe {

public static void main(String[] args) {
final Random random = new Random(System.currentTimeMillis());
final Map<String, Integer> m = new HashMap<String, Integer>();
Integer expected = Integer.valueOf(4711);
m.put(“foo”, expected);
new Thread() {
public void run() {
for (;;) {
int nextInt = random.nextInt();
m.put(String.valueOf(nextInt), Integer.valueOf(nextInt));


for (;;) {
Integer actual = m.get(“foo”);
if (actual != expected) {
throw new RuntimeException(“Got ” + actual + ” (map size is ” + m.size() + “)”);



The code puts the value 4711 for key “foo” and continously retrieves the value for key “foo” from the Map while another thread puts dummy data to it. If the value retrieved from the map is not 4711 the method will throw an Exception.

Copy & compile this code if you are sure that java’s standard collections (like HashMap/ArrayList/…) are thread-safe.

This entry was posted in Java, Tips. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s