i have created an async Task-Thread which creates inside with “Executors.newFixedThreadPool(8)” 8-Worker-Threads for long running jobs. Lets say i have 8 long running jobs, all works fine. All 8 Worker-Jobs complete in for example 10seconds. The Problem is now, if i set the FixedThreadPoolSize to 7 (One Thread less than my amount of Jobs) and i get again my 8 Jobs. It took not round about 10 seconds, it took nearly 70seconds. But why is this so? It looks like there are no more threads available from the pool. But the 7 Threads before are done. And for the last Thread he took 60seconds.
My TaskThread looks like this:
public TaskThread(ExecutorService executorService, List<String> workerJobs) {
this.workerJobs = workerJobs;
this.executorService = Executors.newFixedThreadPool(7, Thread.ofVirtual().name("Thread-", 1).factory());
}
@Override
public void run() {
List<CompletableFuture<String>> jobs = workerJobs.stream().map(job ->
CompletableFuture.supplyAsync(new WorkerJob(),executorService)
).toList();
List<String> taskResultModels = jobs
.stream()
.map(CompletableFuture::join)
.toList();
//Save result to DB
}
}
And my WorkerThread like this:
public class WorkerJob implements Supplier<String> {
@Override
public String get() {
try{
return "Long Running Job";
}catch(Exception e){
return "Error";
}
}
}
I start the TaskThread also with an ExecutorService:
Executors.newSingleThreadExecutor(new TaskThread()).submit()
Stargate is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.