0

I have this situation in Java:

On internal modules called I. A big module Z that receives messages by DBus from I. This big module Z communicate with a external server E (for every message received by Dbus).

By DBus architecture, every time it is done a request, in Z module it is created a new Thread to handle it.

What is the best approach to communicate with 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 ?

Thanks in advance João

joao
  • 97
  • 1
  • 10
  • I wouldn't create a new thread for every event that comes in. Instead, use an event-dispatcher that uses a pool of Threads (like an Executor as suggested by user949300). – Christopher Schultz Apr 18 '12 at 16:45

1 Answers1

0

I know nothing about dbus, so take this with a grain of salt.

I would not choose option B, simply because of Unit Testing. With option A (or C) you could switch in a "MockSendToExternalServer" that simply logs or notes the messages that are being "sent", and the unit test would be to look at those messages.

I would strongly tend towards option C, because then you could use the java.util.concurrent ConcurrencyUtilities such as ExecutorService. For your first pass implementation, use a simple single threaded queue, (e.g. Executors.newSingleThreadedExecutor) but, if/when you need more threads you could add them, e.g. Executors.newFixedThreadPool().

user949300
  • 15,364
  • 7
  • 35
  • 66
  • The problem is.. option C I have to make one class for each method that I have to communicate with the External Server... This is not correct, it isn't ? – joao Apr 18 '12 at 16:30
  • You would probably make one _instance_ of the Runnable per message. But you might be able to use the same Class to handle all of them. (Here I'm guessing a bit cause I don't know your details at all) – user949300 Apr 18 '12 at 16:52
  • Imagine this: I have a class then communicate with External Server.. that have several methods like: GetListOfCars(); GetListOfBikes(); GetListOfXPTO(); – joao Apr 18 '12 at 16:57
  • If the methods are really that similar, the class could take an Enum (or Class, or SQL query string) in the constructor corresponding to Cars, Bikes, XPTO etc. But it there is more fancy stuff going on, then you probably want a separate class for each. You could simplify access by using a single factory method `getMyRunnable(args...)` to return the appropriate Runnable class. So, the implementation has multiple classes, but the user need only know about the factory. – user949300 Apr 18 '12 at 17:50