Home > DeveloperSection > Forums > wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?
Ashish Pandey

Total Post:128

Points:898
Posted on    December-25-2015 11:37 PM

 Java Java  Thread  Threading  Multiple Threading 
Ratings:


 1 Reply(s)
 226  View(s)
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?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    December-25-2015 11:44 PM

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();
  }
}

Don't want to miss updates? Please click the below button!

Follow MindStick