commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Torsten Curdt <>
Subject concurrency and starting a synchronized block
Date Thu, 10 Feb 2005 13:07:02 GMT
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

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.


View raw message