Search code examples
javaconcurrenthashmap

synchronised block for concurrent hashmap


When using a concurrent hashmap do i need to wrap the put around a synchronised block, is there a chance of a race condition:

    synchronized(lock) {
        if(this.map.get(id) != null) {
            throw new Exception();
        }
        this.map.put(id, number);
        return true;
    }

Solution

  • When using ConcurrentHashMap, you should not synchronize as you did in the example above.

    By synchronizing on the map, you are losing the benefits of using ConcurrentHashMap, that does not lock the entire table for every access.

    What you should do in your case is to use the atomic operation putIfAbsent.

    What you gain is throughput for the map when using in multi threaded manner.