I have the following scenario .
I have incoming file download requests and each download is happening in different thread until pool size is exceeded. And after a download completed, a processor processes the downloaded item. So I created the following. I wonder if uses of thread and executors make sense
DownloadTaskProcessor
public class DownloadTaskEnqueuer {
private static final BlockingQueue<Task> downloadQueue = new LinkedBlockingQueue<>();
private static final BlockingQueue<Task> processQueue = new LinkedBlockingQueue<>();
private static final ExecutorService executor = Executors.newCachedThreadPool();
public void offer(Task task) {
return downloadQueue.offer(task);
}
public void createPool(int size) {
for (int i = 0; i < size; i++) {
executor.execute(new DownloadTask(downloadQueue, processQueue);
executor.execute(new ProcessTask(processQueue));
}
}
}
Download task
public class DownloadTask implements Runnable {
private BlockingQueue<Task> downloadQueue;
private BlockingQueue<Task> processQueue;
// constructor for initing two queue
public void offer(Task task) {
return processQueue.offer(task);
}
@Override
public void run() {
while (true) {
Task task = downloadQueue.poll();
if (task != null) {
task.getDownloadTask().download();
offer(task);
} else {
// sleep 250 ms
}
}
}
}
Process task
public class ProcessTask implements Runnable {
private BlockingQueue<Task> processQueue;
// constructor for initing queue
@Override
public void run() {
while (true) {
Task task = processQueue.poll();
if (task != null) {
task.getProcessTask().process();
} else {
// sleep 250 ms
}
}
}
}
Use case (pseudo)
createPool(10);
listener.listen((task) -> {
downloadTaskEnqueuer.offer(task);
}
Task
implementation, otherwise looks quite good to me without testing it. Check whetherpoll
can actually returnnull
. \$\endgroup\$