I am using ExecutorService in my class to async a few Callable tasks and then once all the tasks are complete , complete the parent process. Something like this
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
class SampleService implements Callable<String>{
private String dayOfWeek;
public SampleService(String dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
@Override
public String call() throws Exception {
if("Holiday".equals(dayOfWeek)){
throw new RuntimeException("Holiday is not valid day of week");
} else{
Random random = new Random();
int sleepTime = random.nextInt(60000);
Thread.sleep(sleepTime);
System.out.println("Thread "+dayOfWeek+" slept for "+sleepTime);
return dayOfWeek+" is complete";
}
}
}
class Scratch {
static ExecutorService executor = null;
public Scratch() {
executor = Executors.newFixedThreadPool(8);
}
public static void main(String[] args) {
List<String> days = Arrays.asList("Monday","Tuesday","Wednesday","Thursday","Friday","Holiday");
List<Future<String>> completables = days.stream()
.map(p -> createFuture(p,executor))
.collect(Collectors.toList());
long startTime = System.currentTimeMillis();
while(true || (System.currentTimeMillis()-startTime) < 60000){
boolean complete = true;
for(Future<String> future : completables){
complete = complete && future.isDone(); // check if future is done
}
if(complete){
System.out.println(" all tasks complete");
break;
}
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken to get response from all threads "+ (endTime - startTime));
try{
for(Future<String> future : completables){
String text = future.get();
System.out.println(text);
}
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Future<String> createFuture(String p, ExecutorService executor) {
SampleService service = new SampleService(p);
return executor.submit(service);
}
}
It is working as expected.
The above example is just from a scratch file but i have something very similar. now i have kept the ThreadPoolExecutor as an instance object as it is being called multiple times and i do not want to create a new executor for each call. I would like to know are there any implications if i do not terminate or shutdown the executor when the main service class is terminated/ready for GC. I wanted to use the finalize method but it is deprecated now. So in this case what is the best approach to shutdown the executor when the enclosing class is GC without using finalize method?