Below is my my code implementation using ExecutorService
public void startDownloading(DownloadInfo downloadInfo) {
int messageSentToNextQueue = 0;
ExecutorService downloadExecutor = Executors.newSingleThreadExecutor();
try {
Callable<Integer> task = () -> {
return fileDownloader.downloadFromSourceLink(downloadInfo);
};
Future<Integer> future = downloadExecutor.submit(task);
try {
if (downloadInfo.getExtension().equals(ScraperConstant.ZIP_EXTENSION)) {
messageSentToNextQueue = future.get(11, TimeUnit.HOURS);
} else if (downloadInfo.getExtension().equals(ScraperConstant.HTML_EXTENSION)) {
messageSentToNextQueue = future.get(10, TimeUnit.MINUTES);
} else {
messageSentToNextQueue = future.get(30, TimeUnit.MINUTES);
}
} catch (Exception e) {
log.error(ex);
downloadExecutor.shutdownNow();
}
} catch (Exception ex) {
log.error(ex);
} finally {
if (!downloadExecutor.isShutdown()) {
downloadExecutor.shutdownNow();
}
}
}
Now I'm creating ExecutorService with SingleThreadExecutor on each method call beacuse in the case of timeOut I can shutdown the service to free all the underlying resources and stop any further processing.
If I use ThreadPoolExecutor and intialize it at class level and reuse it, it will definetly a better approach but in that case if time out happen I have to shutdown complete ExecutorService in order to free resources and it will cause other threads while in processing under that ExecutorService to be stop as well and I also have to Initialize ExecutorService after shutdown.
If Someone suggest some better approach it would be great.