This is my Application class -
@EnableAutoConfiguration
@SpringBootApplication
@Configuration
public class Application implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(Application.class);
@Autowired
private ITestService3 testService3;
public static void main(String[] args) {
System.exit(SpringApplication.exit(SpringApplication.run(Application.class, args)));
@Override
public void run(String... strings) throws Exception {
testService3.multiThreadTest();
}
}
Method -
public void multiThreadTest() {
ThreadPoolExecutor readExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
List<String> files = listFiles(new File("/Users/admin/filesList"), new ArrayList<>());
for (String file : files) {
readExecutor.execute(new FileParser(file));
}
}
Even after all the files are read, the application is not terminated However when i use
System.exit(SpringApplication.exit(SpringApplication.run(Application.class, args)));
Application is terminated and all the threads are killed.
And when i use -
SpringApplication.run(Application.class, args).close();
Threads continue to run even after the application says this -
org.springframework.context.annotation.AnnotationConfigApplicationContext@6eda5c9: startup date [Mon Aug 15 04:42:02 IST 2016]; root of context hierarchy 2016-08-15 04:42:05.390 INFO 36600 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
And then i have to manually kill the application. And the application exits with code 130
Can someone please help me with a way to gracefully shutdown the application.
Thanks
First off, you are not closing the ExecutorService
properly, your multiThreadTest
should look like:
public void multiThreadTest() throws InterruptedException {
ThreadPoolExecutor readExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
List<String> files = listFiles(new File("/Users/admin/filesList"), new ArrayList<>());
for (String file : files) {
readExecutor.execute(new FileParser(file));
}
readExecutor.shutdown();
readExecutor.awaitTermination(5, TimeUnit.MINUTES); // wait for tasks to complete
readExecutor.shutdownNow();
}
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