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).
sort should run in the same thread it is invoked. You can simply check the source code.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With