Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.sort (with Comparator) - same or different thread?

Is the comparator code in the Arrays.sort method called in the same thread as the call to sort or a different thread?

I am asking this in the context of JDK 8.

I think the answer is that it's called in the same thread but I am not 100% sure. I would be glad if the person answering this question provides some references or some other kind of detailed explanation (other than simple Yes or No).

like image 858
peter.petrov Avatar asked Oct 10 '15 20:10

peter.petrov


People also ask

Is the Comparator code in the arrays sort method called in the same thread as the call to sort or a different thread?

sort should run in the same thread it is invoked. You can simply check the source code.

Can we use Comparator with arrays sort?

One of the utility method Arrays. sort() helps us to sort an Array of objects by passing Comparator object, where Comparator holds the sorting logic. Below example shows how to sort an array using Comparator.

How do you sort a string array in descending order in Java using Comparator?

To sort an ArrayList using Comparator override the compare() method provided by the comparator interface. Override the compare() method in such a way that it will reorder an ArrayList in descending order instead of ascending order. Change only in the comparison part for descending order.


1 Answers

The answer is no. Sorting (in Arrays.sort) is implemented with DualPivotQuicksort, from the docs:

This class implements the Dual-Pivot Quicksort algorithm by Vladimir Yaroslavskiy, Jon Bentley, and Josh Bloch. The algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations. All exposed methods are package-private, designed to be invoked from public methods (in class Arrays) after performing any necessary array bounds checks and expanding parameters into the required forms.

and as you can see in the implementation - it doesn't spin up any threads.

Further, there are parallelSort methods which use the ForkJoin common pool in order to perform parallel execution. This is very explicit and as some of the other commenters mentioned already - the chances of the JDK API to be vague regards such an issue are very slim.

like image 89
Nir Alfasi Avatar answered Oct 12 '22 11:10

Nir Alfasi