user1555190
user1555190

Reputation: 3243

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;
    }

Upvotes: 0

Views: 115

Answers (1)

Orr Benyamini
Orr Benyamini

Reputation: 405

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.

Upvotes: 2

Related Questions