WRAP CONCURRENTSKIPLISTSET TO KEEP A FIXED CAPACITY OF THE LATEST VALUES IN A THREAD-SAFE WAY?

Ashish Pandey

Total Post:128

Points:898
Posted by  Ashish Pandey
 615  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. Mayank Tripathi

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!