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

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?
Last updated:12/25/2015 11:44:04 PM

1 Answers

Mayank Tripathi
Mayank Tripathi

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