commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From David Graham <>
Subject Re: concurrency and starting a synchronized block
Date Thu, 10 Feb 2005 14:33:04 GMT
A call to Map.get() may depend on state that can be corrupted by a
concurrent call to Map.put().  You don't know without learning the
implementation details of get().  So, you need to synchronize around both

synchronized(map) {
    Object o = map.get(key);
    if (o == null) {
        map.put(key,new Object());

Have you identified this one synchronized block as a bottleneck in your
application with performance testing?  If not, then why are you worrying
about making micro optimizations that may or may not benefit the

FastHashMap states it is not portable in its javadoc so it should never be
used.  Using non-portable classes defeats the entire purpose of using


--- Torsten Curdt <> wrote:

> Guys, forgive me if this too off topic...
> ...but I thought it is somehow related to
> collections that's why I am bringing it up
> here anyway. I bet someone of you will know....
> Consider this code...
>   Object o = map.get(key);
>   if (o == null) {
>     synchronized(map) {
>       map.put(key,new Object());
>     }
>   }
> 99% of the time the "get"s on the map are going
> to return an object. That's why I would like
> to avoid synchronizing the "get" access.
> Now since a "put" might corrupt the data it
> has to be synchronized.
> Since the "get", the comparison and the "put"
> are not in a synchronized block I might loose
> objects ...but for this particular usecase
> that's ok.
> Now what really got me thinking is the
> concurrent sychronized and non-synchronized
> access.
> What happens when Thread A is in doing a
> "get" while Thread B is entering the
> sychronized block for the "put"?
> I assume that since the map object is not
> locked it will go straight into the "put"
> and bang ...right?
> Somehow this looks like the optimal usecase
> for the FastHashMap from collections ...but
> since this code needs to be very portable
> this might be a problem because of the
> double-checked locking idiom.
> Another option would be using the StaticBucketMap.
> What do you guys think?
> If you consider this too OT please reply off list.
> cheers
> --
> Torsten

> ATTACHMENT part 2 application/pgp-signature name=signature.asc

Do you Yahoo!? 
The all-new My Yahoo! - Get yours free! 

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message