ThreadPoolExecutor and using priority to determine what threads will run

Hello,

I am fairly new to Java, so I apologize if there is an obvious answer.

The ThreadPoolExecutor is a great class for thread management. What I would like to do is have a priority scheme that would determine what thread should be run next. For example, let's say I have 100 threads and a limit of 20 threads. Each thread that is executed should have a mechanism to indicate a priority. When a thread becomes available in the pool, the priority value should be checked to determine which thread to run. This would allow me to get important tasks completed quickly. Right now it appears that there is a FIFO order to threads. I tried wrapping the runnable object in a Thread, but that didn't seem to have an effect.

I am using a Fixed thread Pool:

loThreadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(MAXTHREADS); (MAXTHREADS=20)

I have tried creating a PriorityBlockingQueue with a comparator that compares the thread priority, but nothing seems to work.

public Constructor(){

loThreadPoolExecutor =new ThreadPoolExecutor(MAXTHREADS,MAXTHREADS*2,0,TimeUnit.SECONDS,new PriorityBlockingQueue(11,new PrvComparator()));

}

privateclass PrvComparatorimplements Comparator{

publicint compare(Object o1, Object o2){

// TODO Auto-generated method stub

Thread t1 = (Thread) o1;

Thread t2 = (Thread) o2;

System.out.println("P1="+t1.getPriority()+" P2="+t2.getPriority());

if (t1.getPriority()<t2.getPriority())return -1;

if (t1.getPriority()>t2.getPriority())return 1;

elsereturn 0;

//PriorityBlockingQueue

}

I would appreciate any help.

[2440 byte] By [JWeissmullera] at [2007-11-27 0:02:19]
# 1

What are you trying to prioritize? The order on which tasks come off the work queue, or the order in which they get completed?

Doing the first is simple but restricted. Your tasks are Comparable and define their own priority and you use a PriorityBlockingQueue. But you are restricted to using the execute() method with Runnable's that are Comparable. submit() will wrap the task in a FutureTask that isn't Comparable and so will cause a ClassCastException.

Doing the second is difficult. Even if your threads have different priorities then don't queue for tasks in priority order, so the thread priority when taking a task is irrelevant. You could change the thread priority based on the priority of the task once it starts executing. But Thread priorities are only a hint to the scheduler that you think Thread A is more important than Thread B. On some platforms priorities will have little observable effects - whereas on other it can be drastic if you use priorities that are too high or too low. The mapping from Java priority to OS thread priority is platform specific. See for example http://java.sun.com/javase/6/docs/technotes/guides/vm/thread-priorities.html

davidholmesa at 2007-7-11 15:54:35 > top of Java-index,Core,Core APIs...