2013-07-22 23 views
4

关闭执行程序时,应该在哪里捕获RejectedExecutionExceptions?我想:如何在使用Scala期货时捕获RejectedExecutionException?

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) 

回答

4

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

这执行人悄悄越过RejectedExecutionException:

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

我询问了in this thread

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

我以前有一个设置,单线程执行程序读取一些文件,将工作投入另一个泳池。最初的设计是供料器在提交时阻塞自己。这很好,但不灵活。我想在第二个池中分配一些任务,但是当然提交会阻止在那里。

所以,鉴于阻塞是邪恶的,你必须决定如何处理你的任务,一旦你知道你不能运行它们。

一个答案是,您在启动关机之前等待静止。就我而言,我有一些工作要完成,所以我知道工作何时完成。 Viktor Klang在该主题中的观点是,任务是一直分支并提交的,所以如果有人知道静止意味着什么,那就是应用程序,而不是基础设施。

相关问题