Reputation: 3
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!
Upvotes: 0
Views: 228
Reputation: 27996
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.
Upvotes: 0
Reputation: 2968
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.
Upvotes: 1