Which TaskExecutor to use for async logging?

时间:2017-10-12 10:11:35

标签: java spring multithreading asynchronous spring-async

I have a REST webservice and want to log any incoming and outgoing XML requests. As they can be quite large and I also have to apply some sort of transformation, I'd like to execute that in an async thread.

So far I'm just using @Async annotation on the logger method. That will use the default SimpleAsyncTaskExecutor, which "does not reuse any threads": https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#scheduling-task-executor-types

Question: should I better define my own ThreadPoolTaskExecutor rather than relying on the default simple executor? Would it be wise to have a "reusing threads" executor for the short-lived logging tasks?

Further do consider: I will also be having some async database row updates that should also be executing using @Async, and probably with the same executor.

My main problem is: I don't want to think about a fixed pool size of threads, capacity, throttle limits etc. I just want to tell my routine: "Execute the following logic in an async thread." And just stack anything on it.

Which of the TaskExecutors would I have to use for it, and which configuration should be applied?

Would eg the following executor fit?

@Bean
public ThreadPoolTaskExecutor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(4);
    return executor;
}

2 个答案:

答案 0 :(得分:1)

  

我应该更好地定义自己的ThreadPoolTask​​Executor而不是依赖于默认的简单执行器吗?

使用默认ThreadPoolTaskExecutor,除非您需要对其进行自定义。

  

为短期记录任务设置“重用线程”执行程序是否明智?

是。

  

我不想考虑固定池大小的线程,容量,限制等。我只想告诉我的例程:“在异步线程中执行以下逻辑。”只需堆叠任何东西。

     

我必须使用哪个TaskExecutors,以及应该应用哪些配置?

ThreadPoolTaskExecutor已经足够了。在示例代码中将池大小设置为Runtime.getRuntime().availableProcessors()

答案 1 :(得分:0)