Best data structure in Java when using HashSet as a cache

1.7k views Asked by At

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?

1

There are 1 answers

1
assylias On

One option would be a volatile set:

private volatile Set<String> set = new HashSet<> ();

public void update() {
  Set<String> newSet = getNewData();
  set = newSet;
}

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).