Should java.util.Comparator.compare (T o1, T o2) implementations be thread safe?

Or should I only care when used in parallel implementations such as java.util.Arrays.parallelSort(T[] a, Comparator<? super T> cmp) ?

+4
source share
3 answers

The comparison method, by its nature, is a pure function calculated against objects that can be considered immutable, at least during the sort operation. Mutation of objects during sorting would violate the essential assumption of any sorting algorithm, that is, the order imposed by Comparator is stable throughout the operation.

It follows from the above that, although the comparator must be thread safe when used in parallel, it is usually set without much effort. On the other hand, you need to make sure that it does not contain any unsafe code for one reason or another, for example, using an instance-unsafe instance of a co-author, divided into all calls to compare() .

+5
source

It is always a good idea to make things thread safe. Unlike other answers, IMO may not be thread safe, for example, when Comparator uses an object of type SimpleDateFormat as a member variable that would not be thread safe.

Since someone using a comparator will not deal with concurrency, it is certainly a good idea to make it thread safe.

0
source

You're right. Although in most cases the comparator is either thread-safe in design or used in the same thread, there are also cases where the comparator can be used simultaneously. In parallel, as you mentioned, or in parallel collections, like ConcurrentSkipListMap .

In these cases, obviously, the comparator should be thread safe or synchronized.

0
source

All Articles