[concurrency-interest] Implementing Cache

Tutika Chakravarthy chakritsus at yahoo.com
Fri May 12 03:28:03 EDT 2006


Hi All,
I have seen the sample code to implement cache using
FutureTask and ConcuurentHashMap in one of the threads
in this mailing list :

code snippet : 

public interface Computable<A, V> {
     V compute(A arg) throws Exception;
}

public class Memoize<A, V> implements Computable<A, V>
{
     public Memoize(Computable<A, V> c) {
         this.c = c;
     }
     public V compute(final A arg) throws Exception {
         Future<V> f = cache.get(arg);
         if (f == null) {
             Callable<V> eval = new Callable<V>() {
                 public V call() throws Exception {
                     return c.compute(arg);
                 }
             };
             FutureTask<V> ft = new
FutureTask<V>(eval);
             f = cache.putIfAbsent(arg, ft);
             if (f == null) { f = ft; ft.run(); }
         }
         return f.get();
     }
     private final ConcurrentMap<A, Future<V>> cache =
         new ConcurrentHashMap<A, Future<V>>();
     private final Computable<A, V> c;
}

 I would like to know how put method in Cache can be
 implemented using FutureTask .
 
 My put method will be put(key,value). 
 
 I tried creating a dummy task with callable object
 which returns the value we passed to it  and  it
 worked fine.
 
 Is there any good way of implementing the put method?

 
 Tutika


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


More information about the Concurrency-interest mailing list