Re: SingleThreadExecutor and PriorityBlockingQueue
On May 1, 5:44 pm, coffeymex <coffey...@gmail.com> wrote:
See the constructor to ThreadPoolExecutor-- as the last parameter,
you can specify the flavour of queue.
Thanks for your reply, Neil.
It true that you can specify the queue as the last parameter to
ThreadPoolExecutor but in this case it does not solve the problem. The
sample code below compiles without errors but when run the
PriorityBlockingQueue will not work because the actual elements
inserted into the queue are of type java.util.concurrent.FutureTask
which does not implement Comparable.
I guess that I could extend the ThreadPoolExecutor and overwrite the
relevant methods to create comparable future tasks. I does not seem
trivial though. So I'm still wondering why Brian Goetz in "Java
Concurrency in Practice" says it can be done (and thinks it's so
trivial that he does not need to mention how).
Am I overlooking something obvious?
/Morten
public class PriorityQueueExecutor {
static class Bar implements Callable<Integer>, Comparable<Bar> {
private int i;
public Bar(int i) { this.i = i; }
public int compareTo(Bar o) {
return i - o.i;
}
public String toString() {
return "Bar: " + i;
}
public Integer call() throws Exception {
Thread.sleep(i);
System.out.println("Bar: " + i + " done!");
return i;
}
}
public static void main(String[] args) {
ExecutorService executor =
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new PriorityBlockingQueue<Runnable>());
Future<Integer> f1000 = executor.submit(new Bar(1000));
Future<Integer> f100 = executor.submit(new Bar(100));
Future<Integer> f200 = executor.submit(new Bar(200));
}
}