Skip to content

Commit

Permalink
fix issue with threads that are not terminated after the run
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmitriusan committed Nov 24, 2023
1 parent 539a303 commit 97f452d
Showing 1 changed file with 15 additions and 19 deletions.
34 changes: 15 additions & 19 deletions hawk/src/main/java/io/irw/launcher/Launcher.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package io.irw.launcher;

import io.irw.hawk.HawkApp;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
Expand All @@ -15,25 +13,23 @@ public class Launcher {

public static void main(String[] args) {
try (ExecutorService executorService = Executors.newCachedThreadPool()) {
// Start the Spring Boot application in a separate thread
Future<ConfigurableApplicationContext> future = executorService.submit(() -> {
return SpringApplication.run(HawkApp.class, args);
});

// Get the application context from the future and manage its lifecycle
ConfigurableApplicationContext hawkAppContext = future.get();
// Perform any necessary operations with hawkAppContext
// Start the first Spring Boot application in a separate thread
executorService.submit(() -> {
ConfigurableApplicationContext hawkAppContext = SpringApplication.run(HawkApp.class, args);
hawkAppContext.close();
});

// Close the application context gracefully
Runtime.getRuntime()
.addShutdownHook(new Thread(hawkAppContext::close));
} catch (InterruptedException e) {
Thread.currentThread()
.interrupt(); // Preserve interrupt status
throw new RuntimeException("Thread interrupted", e);
} catch (ExecutionException e) {
throw new RuntimeException("Execution exception in application startup", e);
// Shutdown the executor service gracefully when both applications are done
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
Thread.currentThread()
.interrupt();
}
}
}
}


}

0 comments on commit 97f452d

Please sign in to comment.