5

I'm reading the book "Java SE 8 for the really impatient", in the first chapter I came across with the next exercise question:

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

I've searched the javadoc for the Arrays.sort overloading which takes a Comparator argument but it doesn't specify anything about threads. I assume that for performance reasons that code could be executed in another thread, but it is just a guess.

1
  • 5
    Its called on the same thread. Commented May 21, 2014 at 4:51

3 Answers 3

5

You can always test it by logging the id of Thread.currentThread().

Add something this just before calling sort() and in your compare() method.

logger.debug("Thread # " + Thread.currentThread().getId());
Sign up to request clarification or add additional context in comments.

Comments

4

Imagine you have code to get the largest element in an array:

int[] array = new int[] {.........};
/// Few/many lines of code between...
Arrays.sort(array);
int largest = array[array.length - 1];

If sorting were spawned in another thread, you'd have a race condition -- would you sort the array first, or would largest get assigned to first? You could avoid that problem by locking array, but what happens if the code you're running in already locked array? You can block the original thread using join(), but then you've pretty much defeated the purpose of spawning another thread, as your code would act exactly the same way as if there were no additional thread spawned.

For Arrays#sort(), the sorting takes place in the original thread, as there really isn't much point in spawning another thread. Your thread will block until the sorting is complete, just like for any other piece of code.

The closest thing to spawning another thread to sort in is the Arrays#parallelSort() method introduced in Java 8. This still acts pretty much the same as the regular Arrays#sort(), as it blocks your current thread until the sorting is done, but there are threads spawned in the background to help sort the array. For larger datasets, I'd expect an improvement of around the number of threads that were spawned, minus whatever threading overhead there might be.

3 Comments

The threading would happen inside sort. sort would join on the threads it created before returning.
@SotiriosDelimanolis But for sort(), what's the point of spawning another thread if you're just going to block the original thread anyways?
@SotiriosDelimanolis Oh wait, I see what you're saying... Let me edit my answer.
0

In the first test the code will run in single Thread.

In the second test the code will run in multiple Threads.

@Test
public void shouldSortInSingleThread() {

    List<String> labels = new ArrayList<String>();
    IntStream.range(0, 50000).forEach(nbr -> labels.add("str" + nbr));
    System.out.println(Thread.currentThread());
    Arrays.sort(labels.toArray(new String[] {}), (String first,
            String second) -> {
        System.out.println(Thread.currentThread());
        return Integer.compare(first.length(), second.length());

    });

}

@Test
public void shouldSortInParallel() {

    List<String> labels = new ArrayList<String>();
    IntStream.range(0, 50000).forEach(nbr -> labels.add("str" + nbr));

    System.out.println(Thread.currentThread());
    Arrays.parallelSort(labels.toArray(new String[] {}), (String first,
            String second) -> {
        System.out.println(Thread.currentThread());
        return Integer.compare(first.length(), second.length());

    });

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.