2012-04-11 40 views
0

嗨,大家好:这个问题涉及到线程,客户端,Netty和Ning。Executor无法从线程获取自己的线程关闭

背景

宁库是一个异步HTTP请求的工具,它使我们能够建立请求,他们排队,并异步处理它们。它依赖于一些库,比如下面粘贴的JBoss/Netty代码。

问题

我最近碰到这是由该位在JBoss/Netty的ExecutorUtil类代码抛出一个线程关闭例外跑。

这个类看起来基本上是一个在Netty中结束线程的工具。

这种方法在我使用的网络客户端(由Ning提供支持)中导致了一个错误,这是因为我试图关闭该客户端响应的处理程序内部的HttpClient。

问题

什么是这个代码块试图避免死锁的意义是什么?详情请参阅this code url

// Check dead lock. 
    final Executor currentParent = DeadLockProofWorker.PARENT.get(); 
    if (currentParent != null) { 
     for (Executor e: executorsCopy) { 
      if (e == currentParent) { 
       throw new IllegalStateException(
         "An Executor cannot be shut down from the thread " + 
         "acquired from itself. Please make sure you are " + 
         "not calling releaseExternalResources() from an " + 
         "I/O worker thread."); 
      } 
     } 
    } 

回答

2

在网状你不准关机从IO线程内的执行人(如异常是告诉你了;)),这是因为你将不得不看到一个死锁的风险。如果你真的想从一个处理程序中关闭Executor,你需要在一个新的线程中完成它。例如:

public void messageReceived(...) { 
    // in IO-Thread 
    new Thread(new Runnable() { 
     public void run() { 
      //....shutdown here 
     } 
    }).start(); 
} 
+0

线程的分离如何防止死锁。我会想象,如果我们从外部线程调用close,则存在同样的问题..?感谢您的回答。 – jayunit100 2012-04-12 11:53:50

+1

Netty调用ExecutorService.shutdown()来终止当所有提交的任务完成时返回的执行程序。您不能关闭IO-Thread的执行程序,因为ExecutorService.shutdown()将等待已调用shutdown的IO-Thread返回。结果是死锁。诺曼的建议起作用,因为新线程可以等待所有IO线程返回。 – johnstlr 2012-04-13 08:22:20