0

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.

njosa
  • 113
  • 9

2 Answers2

3

Are you looking to implement some form of caching mechanism? If so, there's no need to reinvent the wheel. You can use some cache implementation, like EhCache.

Please, take a look at this thread: similar question about collections with timeout (caches)

Community
  • 1
  • 1
Filipe Fedalto
  • 2,540
  • 1
  • 18
  • 21
  • Thank you for you help, that thread really helped me understand what I really need here. – njosa Aug 15 '12 at 16:17
2

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 putIfAbsent method but you can use the CacheLoader or provide a Callable to generate a value if needed.

String value = cache.get("key", new Callable<String>() { ... });

The callable would be called if cache did not contain a value for the given key.

Stephan
  • 7,360
  • 37
  • 46
  • Guava Cache looks like something that would do the trick for me. One thing I didn't mention in my question is that I need to know if the key was already present in cache when calling `cache.get(...)`. To be precise I need atomic put-if-absent with return info about the prior presence of the key in cache. The only solution I was able to find is to use cache as a map: `value = cache.asMap().putIfAbsent(key, value)` In that way I'm loosing Guava self loading operations, but I'm using their timeout mechanism. What do you think about that? – njosa Aug 15 '12 at 16:15
  • @njosa: If you really need the information "I inserted it but it was absent before" then I guess you will have no other choice. If you only want to make sure that the value is indeed in the map when requested later, the `cache.get(String, Callable)` method is better. The `Callable` will be called and generates the value when requested and absent. So it is transparent for the caller. If you just need the information whether an item is currently present `getIfPresent()` might be helpful. – Stephan Aug 15 '12 at 19:00