Skip to content
This repository has been archived by the owner on Mar 1, 2023. It is now read-only.

Commit

Permalink
Improve thread pool usage
Browse files Browse the repository at this point in the history
Improve the thread pool usage by:

- shutting down the thread pool after the compiliation finished instead
of keeping the threads around
- giving the threads a helpful name
- marking the threads a daemon threads
  • Loading branch information
marschall committed Jul 25, 2021
1 parent 88d25a7 commit add0487
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/main/java/com/alexnederlof/jasperreport/JasperReporter.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JRException;
Expand Down Expand Up @@ -409,10 +412,11 @@ private void createDestination(File destinationDirectory) throws MojoExecutionEx
}

private void executeTasks(List<CompileTask> tasks) throws MojoExecutionException {
ExecutorService threadPool = newThreadPool();
try {
long t1 = System.currentTimeMillis();
List<Future<Void>> output =
Executors.newFixedThreadPool(numberOfThreads).invokeAll(tasks);
threadPool.invokeAll(tasks);
long time = (System.currentTimeMillis() - t1);
log.info("Generated " + output.size() + " jasper reports in " + (time / 1000.0) + " seconds");
checkForExceptions(output);
Expand All @@ -429,6 +433,13 @@ private void executeTasks(List<CompileTask> tasks) throws MojoExecutionException
throw new MojoExecutionException("Error while compiling Jasper reports", e);
}
}
finally {
threadPool.shutdown();
}
}

private ExecutorService newThreadPool() {
return Executors.newFixedThreadPool(numberOfThreads, new JasperReporterThreadFactory());
}

private void checkForExceptions(List<Future<Void>> output) throws InterruptedException, ExecutionException {
Expand All @@ -454,4 +465,20 @@ private boolean isSkip()
{
return skip;
}

/**
* Thread factory the compile threads. Sets the thread name and marks it as a daemon thread.
*/
private static final class JasperReporterThreadFactory implements ThreadFactory {

private static final AtomicInteger THREAD_COUNTER = new AtomicInteger();

@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "jasper-compiler-" + THREAD_COUNTER.incrementAndGet());
thread.setDaemon(true);
return thread;
}

}
}

0 comments on commit add0487

Please sign in to comment.