For batching works, in other words, executing works which takes for a long time, we often use the Async. In this case, We can use @Async easily in Spring Framework. But, using @Async is so dangerous without customizing @Async. So, today, I am going to talk about the way that is how to custumize @Async(TaskExecutor).

At first, Why is using @Async dangerous? If you use @Async expect customization, Spring Framework runs @Async with SimpleAsynTaskExecutor which is a basic class for Async. Actually, In your company, using the SimpleAsynTaskExecutor is very bad because whenever you execute asynchronous working which has lots of jobs, Spring Framework always makes new workers that even don’t have a job which is to cache it. So, using @Async without customization is very dangerous because making new threads consume many resources than other works.

Then, how do we customize the @Async? It is to make @Bean of ThreadPoolTaskExecutor and to return this bean. ThreadPoolTaskExecutor helps us to customize almost options of the thread provied by Java.

[code 1]

pic1 [pic 1]

What functions do options have each other?

  1. setCorePoolSize
    • public void setCorePoolSize(int corePoolSize)
    • Set the ThreadPoolExecutor’s core pool size. Default is 1.
    • This setting can be modified at runtime, for example through JMX.
  2. setQueueCapacity
    • public void setQueueCapacity(int queueCapacity)
    • Set the capacity for the ThreadPoolExecutor’s BlockingQueue. Default is Integer.MAX_VALUE.
    • Any positive value will lead to a LinkedBlockingQueue instance; any other value will lead to a SynchronousQueue instance.
  3. setMaxPoolSize
    • public void setMaxPoolSize(int maxPoolSize)
    • Set the ThreadPoolExecutor’s maximum pool size. Default is Integer.MAX_VALUE.
    • This setting can be modified at runtime, for example through JMX.

If you use @Async like this, your application works more stable and have more high perfomance than before.