I need some Java collection which holds String values and has synchronized method for adding an element if it doesn’t exist already (something like addIfAbsent is for ArrayList). Collection would be under heavy-traffic. Also I would like to have some timeout mechanism after which entry in a collection expires. Timeout should be around 5 seconds.
Any suggestions for elegant solution? Choice of collection without timeout mechanism would be helpful too.
Thanks for your help.
Interpreting time-out as a time value after which an item inserted into the collection will be removed, maybe the Guava Cache implementation is suited to your needs? It doesn’t directly expose a
putIfAbsentmethod but you can use theCacheLoaderor provide aCallableto generate a value if needed.The callable would be called if
cachedid not contain a value for the givenkey.