I am having a Spring-boot application which contains following:
1. REST-API
2. One thread running from start will execute one service BS (background service we can say)
Note: BS have code to create 10 child thread which runs asynchronously to get things done.
Requirement:
1. BS is independent thread which will run throughout the application with main thread.
2. Child thread : will be created in BS and will get collapsed in BS once things done.
Problem: My thread BS needs to sleep(or you can say in wait state) if no work is pending and get back(notify) as and when work come. For this, I have used traditional way wait...notify but while waiting BS thread, the 10 child threads are executing the same code which BS thread is executing. I think thread pool management is not handled properly.
Help appreciate
BS Thread : ThreadPoolTaskExecutor & CommandLineRunner with connection pool set to 1
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("BS Thread:");
executor.initialize();
return executor;
Child Thread : 10 threads created using following code:
ExecutorService service = Executors.newFixedThreadPool(10);
for (BSChildExecutor jobs : listOfJobs) {
service.submit(jobs);
}
service.shutdown();`
I think you have a flaw in your design. The flow you wanted to achieve can be superly simplified.
First, you've added BS which is not required at all. Typical BS are processes include logging, system monitoring, scheduling, notification etc.
In your case, BS is inherently provided by the Thread pool.
Create a Thread pool of X size which meets your requirement which will never die till you gracefully shut down your Spring Application.
Since REST API is the triggering point for your listOfJobs to be executed, Whenever new job(s) comes you keep submitting to the pool.
Snippet to shutdown thread pool gracefully while gracefully shutting down Spring Application
public void onApplicationEvent(ContextClosedEvent event) {
this.connector.pause();
Executor executor = this.connector.getProtocolHandler().getExecutor();
if (executor instanceof ThreadPoolExecutor) {
try {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
threadPoolExecutor.shutdown();
if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
log.warn("Thread pool did not shut down gracefully within "
+ TIMEOUT + " seconds. Proceeding with forceful shutdown");
threadPoolExecutor.shutdownNow();
if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
log.error("Thread pool did not terminate");
}
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With