2012-04-18 55 views
0

我这种情况在Java中:Java的最佳方法(线程,和的DBus的HttpRequest)

在内部模块调用一 通过的DBus从一 这个大模Z通讯接收消息的大模Z一个外部服务器E(用于Dbus收到的每条消息)。

通过DBus架构,每当它完成一个请求时,在Z模块中就会创建一个新的线程来处理它。

什么是与E沟通的最佳方法?

a) Make a class with a method SendToExternalServer(). this method will be called every time that have a new DBus message. 
    i) The method has only one HttpUrlConnection. 
    ii) The method create a differente HttpUrlConnection instance every time is called. 

b) Same situation on a) but now the method SendToExternalServer() is static 
    i) (same situations) 
    ii) (same situations) 

c) Same situation on a) but the class extends the interface Runnable 
    i) (same situation) 
    ii) (same situation) 


d) OTHER ? 

在此先感谢 若昂

+0

我不会为每个进入的事件创建一个新线程,而是使用一个使用线程池的事件分派器(如user949300所建议的执行程序)。 – 2012-04-18 16:45:29

回答

0

我一无所知DBUS,所以借此与一粒盐。

我会不是选择选项B,只是因为单元测试。使用选项A(或C),你可以切换一个“MockSendToExternalServer”,它只需记录或记录正在“发送”的消息,单元测试就是查看这些消息。

我强烈倾向于选项C,因为那样你可以使用java.util.concurrent ConcurrencyUtilities,如ExecutorService。对于第一次执行,使用一个简单的单线程队列(例如Executors.newSingleThreadedExecutor),但是如果/当您需要更多的线程时,您可以添加它们。 Executors.newFixedThreadPool()

+0

问题是..选项C我必须为每个要与外部服务器进行通信的方法创建一个类...这不正确,不是吗? – joao 2012-04-18 16:30:53

+0

您可能会为每条消息创建一个Runnable的_instance_。但是你也许可以使用同一个类来处理它们。 (在这里我猜有点因为我根本不知道你的细节) – user949300 2012-04-18 16:52:13

+0

想象一下: 我有一个类,然后与外部服务器通信..有几种方法,如: GetListOfCars(); GetListOfBikes(); GetListOfXPTO(); – joao 2012-04-18 16:57:27