How to supply my own custom Queue to Threadpool and add tasks to the custom queue on demand in Java?

Home / Uncategorized / How to supply my own custom Queue to Threadpool and add tasks to the custom queue on demand in Java?

Question:
How to supply my own custom Queue to Threadpool and add tasks to the custom queue on demand in Java?

Imagine I have one thread and Let’s say its the main thread and a thread pool (Where there are pool of threads). I want to be able to pass my own bounded queue to the thread pool such that the threads inside the thread pool can actually remove the tasks from the queue and process it. Meanwhile, I want my main thread to constantly loop and check if my bounded queue that I passed in to the thread pool is empty (queue of size == 0) and if it is add more tasks and thread pool needs to pick those up as well. I heard that if I use ArrayBlockingQueue and pass it to a ThreadPoolExecutor I can’t use the normal Queue methods to add more tasks. so i am wondering if there is any way to do this in Java using standard data structures from Java itself?

Here is my sample code
BlockingQueue batchOfTasks = new ArrayBlockingQueue(1024);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 8, 15, TimeUnit.SECONDS, batchOfTasks);

Records records = getRecordsFromMessageQueue(); // Imagine external Message Queue like RabbitMQ or Active MQ or something

while(true) {
if(batchOfTasks.isEmpty()) { // I am not sure if this alone is a useful check or should I do threadPoolExecutor.getActiveCount() == 0 ?
records.forEach(record -> threadPoolExecutor.execute(() -> {
Make a Blocking I/O call;
}));
} else {
messageQueue.pause(); // pause getting records from message queue
}
}


Answer:

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *