arpp
arpp

Reputation: 345

Setting up timeouts for every entry that are present in a HashMap

I have a HashMap in which I want to do a specific action for an entry that is added in the HashMap after a time period.

HashMap<K,V> map = new HashMap<>();
void addEntry(K,V) {
    //set timeout for the key-value pair to say 10 seconds
    map.put(K,V);
}

void actionAfterTimeout(K) {
    //do something
    map.remove(K);
}

Say after the timeout occurs i want to do some processing and remove the entry from the map. How should I do it?

Upvotes: 1

Views: 4393

Answers (2)

jr.
jr.

Reputation: 1739

This one will work if you don't want to use multiple threads. It's not threadsafe. It will perform processing on your first hit to the Map after the timeout has occurred.

class TimedMap<K, V>
{

    private Map<K, V> map = new HashMap<>();
    private Map<K, Long> timerMap = new LinkedHashMap<>();
    private static final Long TIMEOUT_IN_MILLIS = 10000;

    public void addEntry( K key, V value )
    {
        checkTimeout();
        map.put( key, value );
        timerMap.remove( key );
        timerMap.put( key, System.currentTimeInMillis() );
    }

    public void getEntry( K key )
    {
        checkTimeout();
        map.get( key );
    }

    private void checkTimeout()
    {
        List<K> removals = new LinkedList<>();
        for( K key : map.keySet() )
        {
            if( ( System.currentTimeMillis() - 
                      timerMap.get( key ) ) > 
                  TIMEOUT_IN_MILLIS )
            {
                removals.add( key );
            }
            else
            {
                break;
            }
        }
        for( K removal : removals )
        {
            actionAfterTimeout( key );
        }
    }

    private void actionAfterTimeout( K key )
    {
        //do something
        map.remove( key );
    }
}

Upvotes: 0

SamC
SamC

Reputation: 31

Use Timer.schedule(TimerTask task, long delay).

HashMap<K,V> map = new HashMap<>();
Timer timer = new Timer();
long timeout = 10_000; // milliseconds

void addEntry(K key, V value) {
    //set timeout for the key-value pair to say 10 seconds
    map.put(key, value);

    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            actionAfterTimeout(key);
        }
    }, timeout);
}

void actionAfterTimeout(K key) {
    //do something
    map.remove(key);
}

Upvotes: 2

Related Questions