自定義動態定時任務線程池(動態線程池大小+週期執行任務)

默認的使用

static ScheduledThreadPoolExecutorDynamic scheduledExecutorService = new ScheduledThreadPoolExecutorDynamic(2 * Runtime.getRuntime().availableProcessors());

但是當創建定時任務超過corepoolsize的大小後,會將任務添加到等待阻塞隊列,我需要的是線程數動態跟任務數一致...

擴展子類代碼:

package com.xxx.kafka.service.schedule;

import java.util.concurrent.*;

/**
 * <Description>
 * 動態定時任務線程池
 * @author CJJ
 * @version 1.0
 * @createDate 2020/01/12 1:15
 */
public class ScheduledThreadPoolExecutorDynamic extends ScheduledThreadPoolExecutor {
    public ScheduledThreadPoolExecutorDynamic(int corePoolSize) {
        super(corePoolSize);
    }

    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
        dynamicCorePoolSize(this);
        return super.scheduleAtFixedRate(command, initialDelay, period, unit);
    }

    private static void dynamicCorePoolSize(ScheduledThreadPoolExecutor scheduledThreadPoolExecutor) {
        int activeCount = scheduledThreadPoolExecutor.getActiveCount();
        int corePoolSize = scheduledThreadPoolExecutor.getCorePoolSize();
        if (activeCount == corePoolSize) {
            scheduledThreadPoolExecutor.setCorePoolSize(corePoolSize + 1);
        } else if (activeCount < corePoolSize - 1) {
            scheduledThreadPoolExecutor.setCorePoolSize(corePoolSize - 1);
        }
    }

    public boolean cancelSchedule(ScheduledFuture scheduledFuture) {
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(true);
            this.setCorePoolSize(this.getCorePoolSize() - 1);
            return true;
        }
        return false;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章