java - RejectedExecutionException 的原因可能是什么

标签 java multithreading

我在我的 tomcat 服务器 (+liferay) 上遇到此异常

java.util.concurrent.RejectedExecutionException

我的课是这样的:

public class SingleExecutor extends ThreadPoolExecutor {
  public SingleExecutor(){
    super(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
  }

  @Override
  public void execute(Runnable command) {
    if(command instanceof AccessLogInsert){
        AccessLogInsert ali = (AccessLogInsert)command;
        ali.setConn(conn);
        ali.setPs(ps);
    }
    super.execute(command);
  }
}

我在 super.execute(command); 行得到了这个异常 当队列已满但 LinkedBlockingQueue 大小为 2^31 时,可能会出现此错误,并且我确信没有那么多命令等待。

一开始一切都很稳定,但在我重新部署 war 后它开始发生。这个类不是 war 的一部分,而是在 tomcat/lib 的一个 jar 中。

您知道为什么会发生这种情况以及如何解决吗?

最佳答案

来自 ThreadPoolExecutor JavaDoc(强调我的)

New tasks submitted in method execute(java.lang.Runnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated. In either case, the execute method invokes the RejectedExecutionHandler.rejectedExecution(java.lang.Runnable, java.util.concurrent.ThreadPoolExecutor) method of its RejectedExecutionHandler. Four predefined handler policies are provided:

  1. In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.
  2. In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.
  3. In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.
  4. In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)

It is possible to define and use other kinds of RejectedExecutionHandler classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies.

因此,重新加载 war 可能会触发 Executor 的关闭。尝试将相关库放入 war 中,以便 Tomcat 的 ClassLoader 有更好的机会正确重新加载您的应用程序。

关于java - RejectedExecutionException 的原因可能是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8183205/

相关文章:

Java : Creating a Thread Pool in the Server application

database - 在分布式系统中锁定文件

c++ - 在线程中像回调一样调用 C

c++ - 使用 2 个线程的代码运行速度比使用 1 个线程慢 6 倍

java - 使用列表获取匹配项索引的有效方法

java - 终身代垃圾收集

java - 在类里面以正确的方式进行设计时遇到问题

java - 在 MacOS 上的 AdoptOpenJDK 上链接 JNA 库时出错

java - fitCenter 算法 ImageView

C++ 静态类成员指的是自身