0

I am trying to run task based on length of string in ascending order. However its not working as expected. Here is code I have tried till now:

import java.util.Comparator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PriorityQueueTest {
    public static void main(String... args) throws InterruptedException {
        BlockingQueue<Runnable> pq = new PriorityBlockingQueue<Runnable>(5,
                new PriorityQueueComparator());
        Runner r1 = new Runner("ABC");
        Runner r2 = new Runner("AB");
        Runner r3 = new Runner("ABCD");

        Runner[] arr = new Runner[] { r1, r2, r3 };

        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 3, 0,
                TimeUnit.SECONDS, pq);

        for (int i = 0; i < arr.length; i++) {
            pool.execute(arr[i]);
        }
        pool.shutdown();

    }
}

class PriorityQueueComparator<T extends Runner> implements Comparator<T> {

    public int compare(Runner o1, Runner o2) {
        if (o1.getName().length() < o2.getName().length()) {
            return 1;
        }
        if (o1.getName().length() > o2.getName().length()) {
            return -1;
        }
        return 0;
    }

}

class Runner implements Runnable {
    private String name;

    public Runner(String sname) {
        this.name = sname;
    }

    public void run() {
        System.out.println(name);
    }

    public String getName() {
        return name;
    }

}

I expected ouput to be

AB
ABC
ABCD

or

ABCD
ABC
AB

based on compareTo() method of my customer Comparator?

I guess custom comparator not getting called.

Please help.

virendrao
  • 1,763
  • 2
  • 22
  • 42
  • That is probably because the `Runner` objects are never sorted because there isn't more then one of them stored in the queue at a time. To do a more relevant test, you should make the tasks last longer, reduce the thread pool's capacity so that the queue will store more then one object at a time. – Titus Aug 31 '15 at 06:56

1 Answers1

1

A PriorityQueue only sorts the tasks in the queue at that moment. It doesn't

  • sort tasks which have started.
  • sort tasks which haven't been added.
  • change the order the tasks complete if you have multiple threads.

If you have a small number of short lived tasks and multiple threads. You shouldn't expect to see much difference.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130