I'm trying to create a map in which the entries time out and get removed after a certain time period.
Basically, <K, V> Map.put(K key, V value, long **time**)
- the entry will be put in the map instantly and will expire after time (ms). I do not need to recover the removed entry at any point in the future but I would like to make sure it's no longer in the map.
For example: map.put("foo", "bar", 60l * 1000l)
will let this key-value pair live in the map for a minute (60long and 1000long).
Attempt: use a ConcurentMap and implement Map.put(K key, V value, long **time**)
via the following:
super.put(key, value)
2. create a thread that sleeps for time (ms)
3. call remove(key)
to remove the entry.
Question: please comment/let me know whether this is a good idea in terms of thread-safety, consistency or any flaws in my attempt. If you think there's a better way to accomplish this, please provide any advice.
Edit: Thanks for the replies, memory is not the issue here, I really only care about the sho开发者_JAVA百科rt life-span of the entries. Thank you.
Is the time an essential part of the problem you're solving? Or is it an implementation detail? If the problem you're solving is one of memory use, two other possibilities spring to mind:
- An LRU Map. There are a number of these on the web.
- A Map backed by WeakReference or SoftReference objects, which allow the GC to collect those items.
EDIT
In that case, there are some existing implementations that might save you some time. For instance:
- TimedHashMap (one implementation)
- TimedHashMap (another implementation)
If you are doing this because of some memory issue (the map is a temporal cache), you should probably consider using soft references (documentation).
Take a look at Guava - it's a collection library from Google. In particular, you want to look at CacheBuilder and its computing maps. One of its features is "time-based expiration of entries, measured since last access or last write", sounds like exactly what you're looking for.
(Edited to talk about CacheBuilder; it's new since I posted this and is more relevant to the question)
精彩评论