Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is a Comparator used in Collections.sort() thread safe?

Tags:

If I create a single instance of a Comparator, can that instance be used across multiple threads to sort collections using Collections.sort()? Or, do I need to create a new instance of the Comparator for each call to Collections.sort() to ensure thread safety?

like image 340
evan Avatar asked May 21 '10 17:05

evan


People also ask

Are comparators thread-safe?

That depends entirely on how you implement the Comparator . If, for example, it has instance variables that are written to or whose contents are changed implicitly during comparison, it would not be threadsafe.

Does collections sort use Comparator?

While using the Comparable interface, we do not need to make any changes to the code. This is because the sort functions of the collections class automatically use the compareTo method in the class. However, while we implement the Comparator interface, we need to use the comparator name along with the sort function.

What collections in Java are thread-safe?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

How can we make a collection thread-safe?

A thread-safe variant of ArrayList in which all mutative operations (e.g., add, set, remove..) are implemented by creating a separate copy of an underlying array. It achieves thread safety by creating a separate copy of the List which is different than vector or other collections used to provide thread-safety.


2 Answers

That depends entirely on how you implement the Comparator. If, for example, it has instance variables that are written to or whose contents are changed implicitly during comparison, it would not be threadsafe.

Most Comparator implementations do no such thing, but one scenario that might reasonably occur is using a SimpleDateFormat to compare Strings that represent dates. Unfortunately, SimpleDateFormat itself is not thread safe.

like image 176
Michael Borgwardt Avatar answered Sep 21 '22 10:09

Michael Borgwardt


Comparator is an interface, it has no inherent concurrency properties. It's up to how you write it if your implementation is threadsafe or not. If everything it does is confined to the scope of the compare method (No Instance or Class level state) and all the resources it uses are threadsafe, then it will itself be threadsafe.

like image 24
Affe Avatar answered Sep 20 '22 10:09

Affe