[concurrency-interest] conditional put

Bob Lee crazybob at crazybob.org
Mon Nov 5 22:19:45 EST 2007


I use ReferenceCache for this sort of thing:
http://google-guice.googlecode.com/svn/trunk/src/com/google/inject/internal/

We're working on a more flexible replacement though.

In the mean time, you can also use a ConcurrentMap<K, Future<V>>.

Future<V> future = map.get(key);
if (future != null) {
  return future.get();
}
Callable<V> callable = ...;
Future<V> future = new FutureTask<V>(callable);
Future<V> fromMap = map.putIfAbsent(key, future);
return (fromMap == null ? future : fromMap).get();

Bob

On 11/5/07, Dhanji R. Prasanna <dhanji at gmail.com> wrote:
> Hi,
>
> CHM is a wonderful abstraction for atomic conditional puts
> (putIfAbsent). However, it does not work well in a lambda-like use
> case (i.e. evaluate if absent).
>
> Is there some way for me to achieve the following:
>
> chm.putIfAbsent(key, new Callable<Value> {
>     //expression that is only evaluated if key is absent
> });
>
> And that this callable is evaluated atomically.
> Thank you,
>
> Dhanji.
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>


More information about the Concurrency-interest mailing list