javaspring-bootthreadpoolexecutor

Best approach to allocate dedicated background thread in Spring Boot


I need to create a dedicated thread listening on DatagramSocket. Old school approach would be to create one during context creation:

@Bean
void beanDef() {
   var thread = new Thread(myRunnable);
   thread.setDaemon(true);
   thread.start();
}

More modern approach would be to create an executor:

@Bean
Executor() {
   var executor = Executors.newSingleThreadExecutor();
    executor.submit(myRunnable);
}

Which one should I prefer?


Solution

  • Something like this would be a modern way to launch a background thread in Spring:

    @Component
    public class MySocketListenerLauncher {
    
     private ExecutorService executorService;
    
     @PostConstruct
     public void init() {
    
      BasicThreadFactory factory = new BasicThreadFactory.Builder()
        .namingPattern("socket-listener-%d").build();
    
      executorService = Executors.newSingleThreadExecutor(factory);
      executorService.execute(new Runnable() {
    
       @Override
       public void run() {
        // ... listen to socket ...
       }
      });
    
      executorService.shutdown();
    
     }
    
     @PreDestroy
     public void shutdown() {
      if (executorService != null) {
       executorService.shutdownNow();
      }
     }
    
    }