【问题标题】:How to catch RejectedExecutionException when using Scala futures?使用 Scala 期货时如何捕获 RejectedExecutionException?
【发布时间】:2013-07-20 21:08:40
【问题描述】:

关闭执行程序时我应该在哪里捕获 RejectedExecutionExceptions ?我试过了:

 future {
        Option(reader.readLine)
      } onComplete {
        case Success(v) =>
        case Failure(e) => e match {
          case ree: RejectedExecutionException =>
          // doesn't work
      }

和:

 try {
        future {
          Option(reader.readLine)
        } onComplete {
          ...
        }
      } catch {
        case ree: RejectedExecutionException =>
          // doesn't work
      }

也不行。仍然得到:

Exception in thread "pool-99-thread-1" java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1768)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:767)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:658)
at scala.concurrent.impl.ExecutionContextImpl.execute(ExecutionContextImpl.scala:105)
at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:37)
at scala.concurrent.impl.Promise$DefaultPromise.tryComplete(Promise.scala:133)
at scala.concurrent.Promise$class.complete(Promise.scala:55)
at scala.concurrent.impl.Promise$DefaultPromise.complete(Promise.scala:58)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:23)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

【问题讨论】:

    标签: scala executorservice futuretask


    【解决方案1】:

    我问过那个in this thread。

    我觉得当前注册的回调应该在关闭时完成,如果它们在同一个执行器上运行的话。 (或者行为应该由政策管理。)(总有一天我会为我描述的内容提交 PR,因为它看起来很自然。)

    我之前有一个设置,其中单线程执行程序读取一些文件并将作业提供给另一个池。最初的设计是让馈线通过阻止提交来限制自己。这没问题,但不够灵活。我想在第二个池上分叉一些任务,但当然提交会在那里阻塞。

    因此,鉴于阻塞是邪恶的,一旦您知道自己无法运行任务,就必须决定如何处理它们。

    一个答案是您在启动关机之前等待静止。就我而言,我有许多工作要完成,所以我知道工作什么时候完成。

    Viktor Klang 在该线程中的观点是,任务一直被分叉和提交,所以如果有人知道静止意味着什么,那就是应用程序,而不是基础架构。

    【讨论】:

      【解决方案2】:

      必须由 RejectedExecutionHandler 处理。 java.util.concurrent.ThreadPoolExecutor.DiscardPolicy 或您的自定义实现。

      这个 executor 默默地传递了 RejectedExecutionException:

      val executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue[Runnable], Executors.defaultThreadFactory, new DiscardPolicy)
      

      【讨论】:

        猜你喜欢
        • 2020-01-20
        • 2018-11-28
        • 2014-01-10
        • 2016-07-27
        • 1970-01-01
        • 1970-01-01
        • 2020-11-05
        • 1970-01-01
        • 2017-07-11
        相关资源
        最近更新 更多