Home > Net >  How to name a thread by receiving parameters in Java SpringBoot?
How to name a thread by receiving parameters in Java SpringBoot?

Time:10-27

all. I'm new to SpringBoot. And now I hope to naming a thread based on the parameter.

Take a simple example, I'm currently using @Async notation to create an Asynchronous Method

@PostMapping
public void requestMethod(@RequestBody String id){
    ...
    asyncMethod(id);    
}
@Async
public void asyncMethod(String id){
    ...
}

Once there is a POST request send to requestMethod, the method will create an asynchronous method in a new thread. The name of the thread is the same as the parameter received as id.

Because there will be many asynchronous methods in the program. And the asynchronous method will run within in an infinite loop. So, I want to terminate the threads based on their name. But how can I do that?

If there is any ambiguous, please let me know. Thanks in advance.

CodePudding user response:

You cannot do that. The best you can do is to specify TaskExecutor and set the thread prefix name there.

  @Bean
  @Qualifier(SOME_PUBLIC_STATIC_FINAL_VARIABLE)
  public Executor myExecutor() {
    int corePoolSize = 4, maxPoolSize = 8;
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    log.info("Will use {}/{} thread pool for {} ", executor.getCorePoolSize(),   executor.getMaxPoolSize(), taskName);
    executor.setThreadNamePrefix(ADD_YOUR_PREFIX_HERE);
    executor.initialize();
    return executor;
  }

And then on your @Async annotation, you specify the Executor such as @Async(SOME_PUBLIC_STATIC_VARIABLE).

CodePudding user response:

Aid Hadzic's answer is correct, but there is another thing it's missing. in your custom ThreadExecutor, you can set a ThreadFactory.

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadFactory(new ThreadFactory() {
               
    AtomicInteger threadCounter = new AtomicInteger(0);
                
    @Override
    public Thread newThread(Runnable r) {
        Thread namedThread = new Thread(r);
        namedThread.setDaemon(true);                        
        namedThread.setName("my-custom-thread-"   threadCounter.incrementAndGet());
        return namedThread;
    }
});

this will produce threads with the specified name, and they will even have increasing numbers as you create more of them.

setting Daemon thread will allow the application to close even if threads are still active (as opposed to User threads which do not allow the application to close).

now, in order to stop a specific thread, i think you would need to store references to the created threads outside of the executor and forcibly stop them, or use CompleteableFuture instead of @Async annotation, but that is outside the scope of this answer.

  • Related