Discussion:
synchronization on ConcurrentHashMap
Ted Yu
2014-01-14 14:55:36 UTC
Permalink
Hi,
I want to get some opinion on the effectiveness of synchronization on ConcurrentHashMap in the following scenario where onlineServers is a ConcurrentHashMap:
synchronized (this.onlineServers) { return Collections.unmodifiableMap(this.onlineServers); }
Can synchronized be safely removed ?
Thanks
Douglas Pearson
2014-01-14 19:32:02 UTC
Permalink
Yes - the synchronized isn't doing anything there.

unmodifiableMap just creates a reference to the underlying map anyway. It's
not like it's taking a snapshot or a copy (in which case that operation
could be made atomic if you really wanted it to be).

Also ConcurrentHashMap is designed to be shared and accessed concurrently
without needing to synchronize access to it.

The only case where it might make sense to have a synchronized statement
there that I can think of is if you had:

synchronized(this) {
return Collections.unmodifiableMap(this.onlineServers) ;
}

which would be protecting against swapping the entire map instance i.e.
somewhere else having:

void setMap(ConcurrentHashMap newMap) {
synchronized(this) {
this.onlineServers = newMap ;
}
}

But that's not what this code is doing.

Doug
Hi,
I want to get some opinion on the effectiveness of synchronization on
ConcurrentHashMap in the following scenario where onlineServers is a
synchronized (this.onlineServers) {
return Collections.unmodifiableMap(this.onlineServers);
}
Can synchronized be safely removed ?
Thanks
Loading...