I have the following piece of code:
public class Test {
List<Future> future = new ArrayList<Future>();
public static void main(String args[]) throws Exception {
Adapter b1 = new Adapter();
final ExecutorService threadPool = Executors.newCachedThreadPool();
for(//iterate for number of files) {
while(data exists in file) {
//Call a function to process and update values in db
future.add(threadPool.submit(new Xyz(b1)));
//read next set of data in file;
}
}
try {
for(Future f: future) {
f.get();
}
}
catch(Exception e) {
throw e;
}
}
}
class Xyz implements Runnable {
private Adapter a1;
public Xyz(Adapter al) {
this.a1=a1;
}
@Override
public void run() {
try {
a1.abc();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
When the number of files is 1 (for loop runs for 1 time), the code runs fine.
But, when the number of files increases, the code never returns back from future.get() method.
Your
Callable::call/Runable::rundoes not return. Otherwise the corresponding future would not block.Additional executor.shutdown or
future.cancelwill thow anInterruptedExceptionto stop the thread processing the object you submitted but it is up to you if to catch it or not. Your are responsible for making the jobs you submitted stop.When you submit thousands Callables/Runnables to a
CachedExecutorthat it might spawn so many threads that your machine gets so slow that you think it takes forever. But you would have noticed that.When dealing with an undefined number of parallelizable tasks i suggest to use a
FixedThreadPoolwith not much more threads that there are cpu cores.Edit: Therefore when you set a breakpoints at
a1.abc();and step forward you will probably find out that it never returns.