简体   繁体   中英

Timeout hashtable Java

I'm still learning programming and came across an interesting task I must do. Your help will be much appreciated as i have no idea how to implement such task and i have been battling with it for a couple of days now...

A class which stores elements in a Hashtable for a defined amount of time. After the time runs out, the value and key must be deleted. Accessing or manipulating a value, resets the timer for that value. All i managed to figure out was use a timer, but I have no idea where to start from . I can't use anything else like Guava MapMaker suggested in other answers.

I'd appreciate your ideas and help guys!

Create a class with a concurrent Hashmap with methods like put, get and remove.

When putting a element, add it to the map and schedule a runnable to remove it after a amount of time. See the SchedulerExecutorService class to do that.

The submit() method of the executor service returns a Future which lets you to cancel the removing process if necessary.

If rolling-your-own solution this will likely involve storing entries in a ConcurrentMap which have a timestamp. You'll then likely have a scheduled job (see ScheduledExecutorService ) which removes stale entries.

This problem has been solved many times by many cache implementations. See Guava's CacheBuilder for one such implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM