事务执行器实现

直接上代码:

// 定义执行接口
public interface AfterCommitExecutor {
    /**
     * 执行器
     *
     * @param runnable
     */
    void execute(Runnable runnable);
}

// 接口实现
public class AfterCommitExecutorImpl extends TransactionSynchronizationAdapter implements AfterCommitExecutor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AfterCommitExecutorImpl.class);

    /**
     * 本地线程列表
     */
    private static final ThreadLocal<List<Runnable>> RUNNABLE_LIST = new ThreadLocal<>();
    /**
     * 创建线程池
     */
    private static final ExecutorService THREAD_POOL = ThreadPoolFactory.getInstance().defaultPool();

    /**
     * 事务执行器
     *
     * @param runnable
     */
    @Override
    public void execute(Runnable runnable) {
        LOGGER.info("Submitting new runnable {} to run after commit", runnable);
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            LOGGER.info("Transaction synchronization is NOT ACTIVE. Executing right now runnable {}", runnable);
            runnable.run();
            return;
        }
        List<Runnable> threadRunnableList = RUNNABLE_LIST.get();
        if (threadRunnableList == null) {
            threadRunnableList = new ArrayList<Runnable>();
            RUNNABLE_LIST.set(threadRunnableList);
            TransactionSynchronizationManager.registerSynchronization(this);
        }
        threadRunnableList.add(runnable);
    }

    /**
     * 事务执行完成后触发下步操作
     */
    @Override
    public void afterCommit() {
        List<Runnable> threadRunnables = RUNNABLE_LIST.get();
        LOGGER.info("Transaction successfully committed, executing {} runnables", threadRunnables.size());
        for (int i = 0; i < threadRunnables.size(); i++) {
            Runnable runnable = threadRunnables.get(i);
            LOGGER.info("Executing runnable {}", runnable);
            try {
                THREAD_POOL.execute(runnable);
            } catch (RuntimeException e) {
                LOGGER.error("Failed to execute runnable " + runnable, e);
            }
        }
    }

    /**
     * 执行任务完成后移除
     *
     * @param status
     */
    @Override
    public void afterCompletion(int status) {
        LOGGER.info("Transaction completed with status {}", status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK");
        RUNNABLE_LIST.remove();
    }

 

// 线程池工厂
public class ThreadPoolFactory {
    /**
     * 单例模式
     */
    private ThreadPoolFactory() {
    }


    /**
     * 获取单例
     *
     * @return
     */
    public static ThreadPoolFactory getInstance() {
        return ThreadPoolFactorySingle.INSTANCE.getInstance();
    }

    /**
     * 枚举创建单例
     */
    private enum ThreadPoolFactorySingle {
        INSTANCE;

        private ThreadPoolFactory threadPoolFactoryInstance;

        ThreadPoolFactorySingle() {
            threadPoolFactoryInstance = new ThreadPoolFactory();
        }

        public ThreadPoolFactory getInstance() {
            return threadPoolFactoryInstance;
        }
    }


    /**
     * 默认获取系统空闲的线程数
     */
    private static final int THREAD_COUNTS = Runtime.getRuntime().availableProcessors();

    /**
     * 默认线程池名称
     */
    private static final String FACTORY_NAME = "DEFAULT_THREAD_POOL";

    /**
     * 默认队列大小
     */
    private static final int QUEUE_SIZE = 3000;

    /**
     * 默认有界队列
     */
    private static final BlockingQueue<Runnable> TASK_QUEUE = new ArrayBlockingQueue<>(QUEUE_SIZE);
    /**
     * 默认线程池,固定大小,有界队列
     */
    private static final ThreadPoolExecutor DEFAULT_THREAD_POOL_EXECUTOR =
            new ThreadPoolExecutor(THREAD_COUNTS + 1, THREAD_COUNTS * 2, 60,
                    TimeUnit.SECONDS, TASK_QUEUE,
                    new ThreadFactoryBuilder().setNameFormat(FACTORY_NAME).build(),
                    new ThreadPoolExecutor.DiscardOldestPolicy());
    /**
     * 自定义线程池
     */
    private static ThreadPoolExecutor THREAD_POOL_EXECUTOR = null;


    /**
     * 创建默认线程池
     *
     * @return
     */
    public ExecutorService defaultPool() {
        return DEFAULT_THREAD_POOL_EXECUTOR;
    }

    /**
     * 创建自定义线程池
     *
     * @return
     */
    public ExecutorService create(int coreSize, int maxCoreSize, int queueSize, String poolName) {
        // 防止并发
        synchronized (this) {
            if (THREAD_POOL_EXECUTOR != null) {
                return THREAD_POOL_EXECUTOR;
            }
            // 强行规定有界队列
            final BlockingQueue<Runnable> TASK_QUEUE = new ArrayBlockingQueue<>(queueSize);
            THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(coreSize, maxCoreSize, 60,
                    TimeUnit.SECONDS, TASK_QUEUE,
                    new ThreadFactoryBuilder().setNameFormat(poolName).build(),
                    new ThreadPoolExecutor.DiscardOldestPolicy());
        }
        return THREAD_POOL_EXECUTOR;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值