Java 线程池的拒绝策略

Java 线程池的拒绝策略

Java 线程池的拒绝策略一共有四种,分别为AbortPolicyCallerRunsPolicyDiscardPolicyDiscardOldestPolicy。下面就来说明这四种策略的不同之处。

下面策略都需要使用 DemoTask 类,该类的代码如下:

package org.gettingreal.juc.learning.executors;

public class DemoTask implements Runnable {

    private int index;

    public DemoTask(int index) {
        this.index = index;
    }

    @Override
    public void run() {
        System.out.println("index: " + index + ",invoke thread: " + Thread.currentThread().getName());

        try {
            // simulate business code.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

AbortPolicy 策略

该策略丢弃任务,并抛出 RejectedExecutionException 异常信息。是线程池默认的拒绝策略。

package org.gettingreal.juc.learning.executors;

import java.util.concurrent.*;

/**
 * AbortPolicy 策略测试
 */
public class AbortPolicyTest {

    public static void main(String[] args) {
        int corePoolSize = 1;
        int maximumPoolSize = 3;
        long keepAliveTime = 60L;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(2);

        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.MILLISECONDS, workQueue, rejectedExecutionHandler);

        for (int i = 0; i < 10; i++) {
            executor.submit(new DemoTask(i));
        }

        executor.shutdown();
    }

}

执行上述代码得到如下输出:

# 输出
index: 0,invoke thread: pool-1-thread-1
index: 4,invoke thread: pool-1-thread-3
index: 3,invoke thread: pool-1-thread-2
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@29453f44 rejected from java.util.concurrent.ThreadPoolExecutor@5cad8086[Running, pool size = 3, active threads = 3, queued tasks = 2, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
	at org.gettingreal.juc.learning.executors.AbortPolicyTest.main(AbortPolicyTest.java:22)
index: 1,invoke thread: pool-1-thread-2
index: 2,invoke thread: pool-1-thread-3

可以看出,只有 5 个任务得到了执行,实际数量就是 maximumPoolSize + workQueue.size() 的值。

CallerRunsPolicy 策略

当触发拒绝策略,只要线程池没有关闭的话,则使用调用线程直接运行任务。一般对于并发比较小,性能要求不高,不允许失败的场景比较适用。但是,由于调用者自己运行任务,如果任务提交速度过快,可能导致程序阻塞,性能堪忧。

package org.gettingreal.juc.learning.executors;

import java.util.concurrent.*;

/**
 * CallerRunsPolicy 策略测试
 */
public class CallerRunsPolicyTest {

    public static void main(String[] args) {
        int corePoolSize = 1;
        int maximumPoolSize = 3;
        long keepAliveTime = 60L;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(2);

        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();

        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.MILLISECONDS, workQueue, rejectedExecutionHandler);

        for (int i = 0; i < 10; i++) {
            executor.submit(new DemoTask(i));
        }

        executor.shutdown();
    }

}

执行上面代码,得到如下输出:

# 输出
index: 0,invoke thread: pool-1-thread-1
index: 4,invoke thread: pool-1-thread-3
index: 5,invoke thread: main
index: 3,invoke thread: pool-1-thread-2
index: 6,invoke thread: main
index: 2,invoke thread: pool-1-thread-3
index: 1,invoke thread: pool-1-thread-1
index: 7,invoke thread: pool-1-thread-3
index: 8,invoke thread: pool-1-thread-1
index: 9,invoke thread: pool-1-thread-4

可以看到里面 main 线程执行相关的任务,所有的任务都得到了执行,并且没有抛出异常。

DiscardPolicy 策略

这个策略是直接丢弃。

package org.gettingreal.juc.learning.executors;

import java.util.concurrent.*;

/**
 * DiscardPolicy 策略测试
 */
public class DiscardPolicyTest {

    public static void main(String[] args) {
        int corePoolSize = 1;
        int maximumPoolSize = 3;
        long keepAliveTime = 60L;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(2);

        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy();

        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.MILLISECONDS, workQueue, rejectedExecutionHandler);

        for (int i = 0; i < 10; i++) {
            executor.submit(new DemoTask(i));
        }

        executor.shutdown();
    }

}

执行上述代码,得到如下输出:

# 输出
index: 0,invoke thread: pool-1-thread-1
index: 3,invoke thread: pool-1-thread-2
index: 4,invoke thread: pool-1-thread-3
index: 1,invoke thread: pool-1-thread-3
index: 2,invoke thread: pool-1-thread-1

可以看出,有 5 个任务被拒绝了,也没有出现错误。

DiscardOldestPolicy 策略

当触发拒绝策略,只要线程池没有关闭的话,丢弃阻塞队列 workQueue 中最老的一个任务,并将新任务加入。

package org.gettingreal.juc.learning.executors;

import java.util.concurrent.*;

public class DiscardOldestPolicyTest {

    public static void main(String[] args) {
        int corePoolSize = 1;
        int maximumPoolSize = 3;
        long keepAliveTime = 60L;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(2);

        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();

        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.MILLISECONDS, workQueue, rejectedExecutionHandler);

        for (int i = 0; i < 10; i++) {
            executor.submit(new DemoTask(i));
        }

        executor.shutdown();
    }
}

执行如上代码,得到如下输出:

index: 0,invoke thread: pool-1-thread-1
index: 4,invoke thread: pool-1-thread-3
index: 3,invoke thread: pool-1-thread-2
index: 8,invoke thread: pool-1-thread-2
index: 9,invoke thread: pool-1-thread-1

可以看出,index 后面的编号是最新加入线程池的任务。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GettingReal

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值