Proper way to start new thread from service layer using spring

JaneXQ :

I have a method that will be rarely called. This method collect garbage in db. I don't want to make user to wait for server response so i decided to call this method from new thread from my service layer. i'm using Spring. Service class:

@Service
@Transactional
public class UploadService {

    @Resource(name = "UploadDAO")
    private UploadDao uploadDao;

Method that i don't want to wait for

public void collectBlobGarbage(){
        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                uploadDao.collectBlobGarbage();
            }
        });
        th.start();
    }

Is it a good way to do like this?

Turbut Alin :

If you have Spring on your classpath you might as well use @Async

@Async
public CompletableFuture<Void> collectBlobGarbage() throws InterruptedException {
    CompletableFuture.completeFuture(uploadDao.collectBlobGarbage());
}

On your main class you need to use @EnableAsync like:

@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

And you need an executor bean:

@Bean
public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("Stackoverflow-");
    executor.initialize();
    return executor;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476226&siteId=1