简体   繁体   中英

Sorting a CopyOnWriteArrayList

I need to maintain a list of objects in a multi-threaded environment. I have read about CopyOnWriteArrayList and it seemed to be an option to go for. The problem is, I needed to sort the list, too. I cannot use Collections.sort() for CopyOnWriteArrayList as it doesn't support the set() operation. I have found few ways to sort the CopyOnWriteArrayList. But performance-wise, they don't look to be good.

My question: is there an alternative data-structure which will come handy in this situation? Basically, I need to keep a sorted list in an multi-threaded environment. A list adapter will use that data structure. So, it should have provide methods like "get(position)".

I recently read about another data structure ConcurrentSkipListSet . Can anyone explain what are the pros and cons of it? Will it be a good fit for my problem?

I know that you ask about performance, and I am not sure on how well my method does on that, but here's what I use:

List arrayList = Arrays.asList(cowArrayList.toArray());
Collections.sort(arrayList, new MyComparator());
cowArrayList.clear();
cowArrayList.addAll(arrayList);

Solution 1: If you want to sort the list during insertion of every element, you can do a binary search and add the element at a sorted location every time. The assumption is that the list is always sorted. Please have a look at http://www.javacreed.com/sorting-a-copyonwritearraylist/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM