• ThreadPoolTaskExecutor is in the Spring Core package, and ThreadPoolExecutor is the JUC in the JDK.
  • ThreadPoolTaskExecutor encapsulates ThreadPoolExecutor.

Take a look at the source code for ThreadPoolTaskExecutor

Take a look at the ThreadPoolExecutor source code

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
Copy the code

Int corePoolSize: The minimum number of threads maintained by the thread pool.

Int maximumPoolSize: The maximum number of threads maintained by the thread pool.

Long keepAliveTime: indicates the keepAliveTime of idle threads.

TimeUnit Unit: indicates the unit of time, including nanoseconds, microseconds, milliseconds, and seconds.

BlockingQueue<Runnable> workQueue: Holds a queue of tasks waiting to be executed.

ThreadFactory: a ThreadFactory

RejectedExecutionHandler Handler: Used to reject the execution of a task

There are four types of rejection strategies:

(1) ThreadPoolExecutor AbortPolicy strategy, is the default strategy, will throw runtime RejectedExecutionException handler was refused.

(2) the ThreadPoolExecutor CallerRunsPolicy strategy, the caller’s thread can perform this task, if the actuators are closed and is discarded.

(3) ThreadPoolExecutor DiscardPolicy strategy, it is impossible to carry out the task will be discarded.

. (4) ThreadPoolExecutor DiscardOldestPolicy strategy, if the execution has not been closed, is located in the work queue head task will be removed, and then retry the executor (if fail again, repeat this process).

This was explained in detail in the previous chapter

Let’s now use ThreadPoolTaskExecutor

Make a tool class

package utils; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.ui.ModelMap; import java.lang.reflect.Method; import java.util.concurrent.CountDownLatch; public class ThreadTool { static ThreadPoolTaskExecutor threadPoolTaskExecutor; static { threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(5); threadPoolTaskExecutor.setMaxPoolSize(10); threadPoolTaskExecutor.setQueueCapacity(100); threadPoolTaskExecutor.initialize(); } /** * Use the thread pool to execute the business method and add the view * @param Tasks counter * @param modelMap view * @param modelName View name * @param service the service to call * Public static void runMethod(CountDownLatch tasks, ModelMap ModelMap, String modelName, Object service, Method method, Object... param){ threadPoolTaskExecutor.submit(new RunInThreadPool( tasks,modelMap,modelName,service,method,param)); }}Copy the code

RunInThreaddPool

package utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.CountDownLatch; public class RunInThreadPool implements Runnable { CountDownLatch countDownLatch; Map modelMap; String keyName; Object service; Method method; Object[] param; /** * @param countDownLatch counter * @param modelMap view * @param keyName parameter name * @param service service to be called * @param method Public RunInThreadPool(CountDownLatch CountDownLatch, Map modelMap, String keyName, Object service, Method method, Object... param) { this.countDownLatch = countDownLatch; this.modelMap = modelMap; this.keyName = keyName; this.service = service; this.method = method; this.param = param; } @Override public void run() { Object result = null; try { Long start = System.currentTimeMillis(); result = method.invoke(service, param); Long end = System.currentTimeMillis(); System.out.println(string. format("%s *** execute (((%s)))), service.getClass(), method.getName(), (end - start), JsonUtils.toJson(param))); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } modelMap.put(keyName, result); countDownLatch.countDown(); }}Copy the code

Actual combat cases:

@RequestMapping("/goodsDetail") public String goodsDetail(GoodsBean goodsBean, PageBean pageBean, ModelMap modelMap) throws Exception { final CountDownLatch latch = new CountDownLatch(7); Method getRelatedGoods = goodsService.getClass().getMethod("getRelatedGoods", GoodsBean.class, String.class); getRelatedGoods.setAccessible(Boolean.TRUE); ThreadTool.runMethod(latch , modelMap, "relatedGoods0", goodsService, getRelatedGoods, goodsBean, "0"); // There are six similar businesses left... . latch.await(); return "production/index"; }Copy the code

Contrast:

    @RequestMapping("/getRelatedGoods")
    @AppController
    public String getRelatedGoods(GoodsBean goodsBean, String show_type,ModelMap modelMap) {
        modelMap.addAttribute("getRelatedGoods",goodsService.getRelatedGoods(goodsBean, show_type));
        return "production/index";
    }
Copy the code