wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?

Total Post:128

Points:898
 867  View(s)
Ratings:
Rate this:
I want to wrap ConcurrentSkipListSet to keep a fixed capacity of the latest (according to Comparator) values:
private int capacity = 100;
// using Integer just for an illustration
private ConcurrentSkipListSet<Integer> intSet = new ConcurrentSkipListSet<>();
Therefore, I implemented put() like this:

// This method should be atomic.
public void put(int value) {
    intSet.add(value);
    if (intSet.size() > capacity)
        intSet.pollFirst();
}
However, this put() is not thread-safe.

Note: No other mutation methods. Of course, I need "read-only" methods like getLast() or getBefore(Integer value).

How to wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?
  1. Post:397

    Points:3117
    Re: wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?

    You're not likely to be able to do this and get the concurrency benefits of ConcurrentSkipListSet. At that point, you might as well just use Collections.synchronizedNavigableSet(TreeSet), at which point you can just write

    synchronized (set) {
      set.add(value);
      if (set.size() > cap) {
        set.pollFirst();
      }
    }

Answer