[concurrency-interest] Questions on ConcurrentHashMap

David Holmes dcholmes at optusnet.com.au
Thu Nov 29 01:20:23 EST 2007


Hi Grace,

> > This won't cause task.run() to execute. Though you could create a custom
> > FutureTask that provides that functionality - ie first getter
> > runs, and uses internal synchronization.
>
>
> 1) Thanks all for catching the fact that it won't execute.  Could you
> explain further this part - " first getter runs, and uses internal
> synchronization" ?  What do you mean by "internal" synchronization?

Simply that you have to use some form of synchronization so that only one
thread will execute run(). eg:

public final void get() ... {
  if (isDone())
    return super.get();
  synchronized(this) {
    if (!isDone())
      run();
  }
  return super.get();
}

That said, I think FutureTask.run() is actually safe to call multiple
times - anything other than the first will just return. But that's an
implementation detail not part of the spec. If you can live with that then
get() can be written simply as

public final void get() {
   run();
   return super.get();
}

> > This doesn't invalidate the map for callers of getValue() that
> > have already retrieved the old map from getMyCache() but have not yet
> > executed get(key) on it.
> >
> I am fine with that.  I just need my map to be in a consistent
> state;i.e. all entries of the map are from previous loading or all
> entries of the map are from new loading.  For instance, if I iterate
> thru the map,  I don't want a map containing half entries of new
> values and half entries with old values.  In between loadings, there
> would be many concurrent gets on the map.

Hmmm. That would depend on the details of iteration and how the clear() can
be interleaved. I don't think you have this consistency guarantee in
general.

> One more question,
>
> FutureTask task = new FutureTask();
>
> If task.get() is called before task.run(), what would happen?
> Does task.get() waits till task.run() is run and finished?

Yes, get() blocks until the result is available or the Future has been
cancelled.

David



More information about the Concurrency-interest mailing list