Java – Managing Threads with a Good Pattern

javamultithreadingmvc

This morning I began writing a minimal chat using Java socket and threads but it took some minutes for me to experience a lot of problems in the MVC management.

Currently I have 3 classes:

  • Main, this is just the main class used for starting the Control.
  • ChatController, I use this for managing Model and View classes (this is a Controller class).
  • Host, a class containing a Socket attribute and two Scanner and PrintStream attributes for reading and writing to and from the socket.

The problem here is which class extending from Thread to let the program both read and write features concurrently. My professor told me to extend the ChatControl (hence, the Controller) class, but I think it is too much hard-coding (and also, I don't like the method/attributes inherited from Thread to be visible from the ChatController class).

So, is it correct extending the Control class from Thread for managing the thread or should I consider to implement another class for tasking this problem (or even trying some other patterns)?

If you need some source, find it on pastebin.

Best Answer

Since it seems you are limited to MVC (re: comment from professor), you may want to look at this from a slightly different direction. Consider a chat received and chat to be sent as "events" that the controller must process and dispatch. The controller can have two queues. One for processing received chats and one for sending them. The network code feeds into and out of these queues. That's at least how I would look at it because it makes the threading a little simpler to handle.

Related Topic