I am writing a java program that needs to handle many URLs.
The following tasks will be performed at each URL. ORDER: upload, analyze, compress
Instead of having one thread to complete all tasks for each URL, I want each task to have a fixed number of threads, so that all tasks will have threads running simultaneously at any given time.
For example, a load job will have multiple threads for retrieving and loading URLs, as soon as one of the URLs is loaded, it will transfer it to the stream in the analytic task and, as soon as it is completed, it will go to the stream in the compression task etc.
I am thinking about using CompletionService in java, since it returns the result right after it is completed, but I'm not sure how it works while my code looks like this:
ExecutorService executor = Executors.newFixedThreadPool(3); CompletionService<DownloadedItem> completionService = new ExecutorCompletionService<DownloadedItem>(executor); //while list has URL do { executor.submit(new DownloadJob(list.getNextURL());//submit to queue for download //} //while there is URL left do { Future<DownloadedItem> downloadedItem = executor.take();//take the result as soon as it finish //what to do here?? //}
My question is: how to transfer the loaded element to the analysis task and do the work there, without waiting for the completion of all load tasks? I am thinking of creating a CompletionService for every job, is this a viable method? If not, is there a better alternative way to solve this? Give examples.
source share