Question

I am implementing a cache with expiry. I am using a ScheduledThreadExecutor for scheduling the removal of entries from cache. My problem is that the executor is never getting shutdown. I have tried executor.shutdown() method in shutdownHook but its not getting executed even after my main program finished execution. I don't prefer finalizer also. My code is given below. I want the closeCache() method to be executed when the main program exits.

public class TimeCacheManual<K,V> {

private final int maxSize;
private final long timeToLive;
private Map<K, V> keyValueMap;
private Map<K,ScheduledFuture > keySchedulerMap;
private Queue<K> keys;
private final ScheduledExecutorService scheduler;
 /*
* creates new instance of TimeBasedEvictionCache.
* @param maxSize must be greater than zero
* @param timeToLive must be greater than zero
* @throws IllegalArgumentException if {@code maxSize<1||timeToLive<1}
* */
public TimeCacheManual(int maxSize,long timeToLive) {
    if(maxSize<1||timeToLive<1){
        throw new IllegalArgumentException();
    }
    this.maxSize = maxSize;
    this.timeToLive = timeToLive;
    keyValueMap = new ConcurrentHashMap<K, V>(maxSize);
    keySchedulerMap = new ConcurrentHashMap<K, ScheduledFuture>(maxSize);
    keys = new ConcurrentLinkedQueue<K>();
    scheduler =  Executors.newScheduledThreadPool(maxSize);

}
/*
 * adds a key value pair to the cache.
 * @param key
 * @param value associated with key
 */
public synchronized void put(K key,V value) {
    if (keyValueMap.containsKey(key)) {
        refreshKey(key);
    }
    else{
        keys.add(key);
    }
    keyValueMap.put(key, value);
    scheduleEviction(key); // schedules eviction of the key after timeToLive
}
/*
* schedules eviction of particular key after timeToLive
* @param key
*/
private void scheduleEviction(final K key){
ScheduledFuture sf= scheduler.schedule( new Runnable(){
        @Override public void run(){
            keys.remove(key);
            keyValueMap.remove(key);
        }
    },
            timeToLive,
            TimeUnit.MILLISECONDS);
    keySchedulerMap.put(key,sf );

}
/*
 * used to get a value associated with a given key. returns null if no value is associated with given key
 * @param key
 * @return value associated with key, null if no value is associated with particular key
 */
public synchronized V get(K key) {
    refreshKey(key);
    scheduleEviction(key);
    return keyValueMap.get(key);
}
/*
 * updates the order of keys according to a particular policy
 * @param key to be refreshed
 */
private void refreshKey(K key){    // refreshing the order of keys
    keySchedulerMap.get(key).cancel(true) ;
    keys.remove(key);            //LRU policy
    keys.add(key);
}
public void closeCache(){
    scheduler.shutdownNow() ;
}

}

Was it helpful?

Solution

thanks for replying. i was creating a library. so it will not know when to call executor.shutdown() unless the user of the library explicitly calls the shutdown(). Anyway i got the solution. I made the executor a daemon thread so that it will get killed automatically when the main program exits. code to make a daemon executor is given below

scheduler =  Executors.newScheduledThreadPool(maxSize,new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    });

Thank you guys. Hope this will help someone

OTHER TIPS

executor.shutdown() closes thread pool only after all already submitted tasks are finished. Looks like you have timer-scheduled tasks which keep executor running. Cancel them, or call shutdownNow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top