---
title: "wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?"  
description: "wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?"  
author: "Anonymous User"  
published: 2015-12-25  
updated: 2015-12-25  
canonical: https://www.mindstick.com/forum/33790/wrap-concurrentskiplistset-to-keep-a-fixed-capacity-of-the-latest-values-in-a-thread-safe-way  
category: "java"  
tags: ["java", "thread", "threading", "multiple threading"]  
reading_time: 1 minute  

---

# 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](https://www.mindstick.com/interview/832/what-is-the-difference-between-the-size-and-capacity-of-a-vector) of the [latest](https://www.mindstick.com/forum/159680/how-can-i-install-the-latest-version-of-sql-server) (according to Comparator) [values](https://www.mindstick.com/forum/327/sum-textbox-values):

```
private int capacity = 100;// using Integer just for an illustrationprivate ConcurrentSkipListSet<Integer> intSet = new ConcurrentSkipListSet<>();
```

Therefore, I implemented [put](https://answers.mindstick.com/qa/111890/can-you-explain-the-difference-between-put-and-post-http-methods)() 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](https://www.mindstick.com/articles/126322/how-to-keep-your-home-safe-while-traveling).\
Note: No other mutation [methods](https://www.mindstick.com/articles/13060/runny-nose-remedy-methods-that-work-best). Of course, I need "read-only" methods like getLast() or getBefore([Integer](https://answers.mindstick.com/qa/113667/write-code-for-roman-to-integer) [value](https://www.mindstick.com/articles/23219/an-optimized-description-adds-value-to-experience-and-in-turn-effectively-guest-posting-packages)).\
How to wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?

## Replies

### Reply by Anonymous User

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();  }}
```


---

Original Source: https://www.mindstick.com/forum/33790/wrap-concurrentskiplistset-to-keep-a-fixed-capacity-of-the-latest-values-in-a-thread-safe-way

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
