My use case is this:
I need to cache a set of strings for frequent read access. The cache is updated by a daemon thread periodically. Moreover, the cache element will never get updated individually, it would always be
set.clear();set.addAll(List)I'm currently using a
HashSet
protected by an ReentrantReadWriteLock
. Is there a better way to do this?
One option would be a volatile set:
This is thread safe (if you don't let other code access the set itself) and does not require locking. One drawback is that you hold both sets in memory until the next GC (not sure how much space is used per entry - to be tested).