commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jörg Schaible <Joerg.Schai...@Elsag-Solutions.com>
Subject RE: concurrency and starting a synchronized block
Date Thu, 10 Feb 2005 13:20:53 GMT
Torsten Curdt wrote on Thursday, February 10, 2005 2:07 PM:

> 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.

then get() twice:

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

since 99% of the time it will not enter the block, the second lookup does not matter ...

Regards,
Jörg

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message