I am building a REST Service and I have the following structure of classes:
public class MyTask implements Runnable {
@Override
public void run() {
//do stuff
}
}
public class RestController {
private MyThreadPool myThreadPool;
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public ResponseEntity<?> getSomething (....){
myThreadPool.getExecutorService().submit(new MyTask(request));
}
}
public class MyThreadPool{
private final static Integer SIZE_OF_POOL = 5;
private final static Integer KEEP_ALIVE= 5000;
private final static Integer QUEUE_SIZE = 50;
private final static Integer MAX_POOL_SIZE = 10;
private BlockingQueue<Runnable> queue = new PriorityBlockingQueue<Runnable>(QUEUE_SIZE); //pass comparator here?
private ExecutorService executorService = new ThreadPoolExecutor(SIZE_OF_POOL, MAX_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, queue, new ThreadPoolExecutor.CallerRunsPolicy());
public ExecutorService getExecutorService() {
return executorService;
}
}
I may have scenarios in my project where my request
object has an integer to represent priority.
I am looking to Submit runnable tasks for execution with this priority value and I am not sure where to implement this logic and how to do it. I know I have to use the PriorityBlockingQueue
somewhere and implement a Comparator
. So do I...
1) Implement in MyThreadPool class 2) Or Implement logic in MyTask
Can you guys please show how to implement this Comparator so that requests with highest priority are executed first?