Swing application using threads based on MVC - java

My application has some Threads that are initiated in Main Class.
And I want to use MVC in this Swing Application.
The Main class waits a socket connection from some client, then when the client is connected I create a telnet object from a Telnet class that I create. And this class has all the shared resources that the threads will use.
After this I start my threads, passing the telnet object as a parameter, so it will be used to syncrhonize the threads.
There are five threads in my application: Client, Management, Server, Node and Agent.
Each one has a specific function.
So this is my scenario.
I want to use MVC in my application to organize these threads more properly, and make the application more easy to maintain.
I've already used MVC in Swing application, but without threads.

Perhaps it's me, but your question still seems quite broad to me, and so I can only offer broad suggestions.
Key in my mind will be how will objects communicate with each other, and I think that this is more important to me than how "Threads" communicate.
Best I think is to use an observer pattern.
If your Threads are created using a SwingWorker, then you have two main ways to communicate back to your Swing application:
You can use the publish/process method pair, where you pass an object into a publish method call, and then make Swing calls, perhaps to change your model's state via the process method. I don't like this approach as well, since coupling is increased, as the SwingWorker must know about the structure and behavior of the view or control code that it calls inside of the process method.
Or you can use the SwingWorker's innate SwingPropertyChangeSupport abilities to allow listeners (here the controller) to be notified of changes in the state of the worker. Then the controller can extract information that has changed and pass it to the model. I tend to favor this approach since for me, it is much easier to loosen coupling.

Related

Java - Swing UI separate socket logic

I become desperate, I develop a simple multi-user chat in Java based on the client-server principle. I already wrote a basic multi-threaded server application and it works great. My problem is the client on the basis of the Swing GUI Toolkit. A basic UI with a runtime loop for receiving messages in the background. My problem is that I want to separate the socket logic from the UI, this means that in the best case I've two different classes one for the socket runtime loop and another to manage the UI. Because of the problem, that the runtime loop must notify/add messages to the UI, they depend on each other.
MessengerView is my main class which contains the swing ui and all depended components. At the moment this class contains also the socket logic, but I want to extract them to an external class.
ClientRuntime the class which should hold the socket logic...
My question is, how could I separate them and how could I connect them? For example I tried swing-like events with registering of methods like this:
addListener(MessageArrivedListener listener);
emitMessageArrivedEvent(String message);
The problem is, that it is very confusing if the count of events raises! As already said my second options is to hold socket logic and ui design in one class, but I think it's a bad idea because it makes it very hard to write unit tests for it or to find bugs...
In my time with C++ I used sometimes friend-classes for this issue, because this makes it possible to access class members of other classes! But this solution is often also very confusing and I found no such option for Java.
So are there any other possibilities to hold the connection between the swing widgets and the socket logic, without storing them in the same class (file)?
how could I separate them and how could I connect them?
Connect them with BlockingQueue - this the first choice when choosing ways to connect threads.
ClientRuntime class must start 2 threads: one takes requests from the blocking queue and sends them to the server, and the second constantly reads the messages from the server through the socket and sends them to the UI thread. The UI thread has already input blocking queue for messages: it is accessed by SwingUtilities.invokeLater(Runnable);. The ClientRuntime class does not access UI queue directly: it calls a method from MessengerView and passes what it received from the socket, a binary array or json string, and that UI method converts it to some Runnable which actually updates the UI.
they depend on each other
Well, they don't really. The "socket" layer only cares about been started, running, posting some messages and stopping.
How all that actually get done/handled it doesn't care about, it just "starts" when told, processes input/output messages, posts notifications and "stops" when asked to.
This is basically an observer pattern, or if you prefer, a producer/consumer pattern.
So the socket layer needs to define a "protocol" of behaviour or contract that it's willing to work with. Part of that contract will be "how" it generates notifications about new messages, either via an observer or perhaps through a blocking/readonly queue - that's up to you to decide.
As for the UI, it's a little more complicated, as Swing is single threaded, so you should not block the UI with long running or blocking operations. This is where something like a SwingWorker would come in handy.
It basically acts a broker between the UI and the mechanism made available by the socket layer to receive messages. Messages come from the socket layer into the SwingWorker, the SwingWorker then publishes them onto the UI's event thread which can then be safely updated onto the UI
Maybe start with Concurrency in Swing and Worker Threads and SwingWorker
My question is, how could I separate them and how could I connect them? For example I tried swing-like events with registering of methods like this:
The problem is, that it is very confusing if the count of events raises!
I don't think so (IMHO). What you want to do is focus on the "class" of events. For example, from the above, you have "life cycle" events and you have "message" events. I'd start by breaking those down into two separate interfaces, as those interested in "message" events probably aren't that interested in "life cycle" events, this way you can compartmentalise the observers.
The important concept you want to try and get your head around is the proper use of `interfaces to define "contracts", this becomes the "public" view of the implementations, allowing you devise different implementations for different purposes as you ideas change and grow. This decouples the code and allows you to change one portion without adversely affecting other parts of the API

Java multithreading and SWING

I'm developing a SWING based Java application with multithreading.
The idea is to create a set of background "tasks/services" to do some tasks repeatedly.
My problem is how to implement multithreading (in the lower level of the application) that can interact with the GUI by displaying SWING components at some conditions.
I know I can use SwingWorker but using that I will turn my application more "gui oriented" wich I don't want to but in the other hand I also don't want to make my multithreading classes depended on GUI classes.
What are the options where?
Thank you in advance.
EDIT
I forgot to mention that this background tasks need to be started in the beginning and cannot be launched by the GUI (like a bootstrap process).
but in the other hand I also don't want to make my multithreading
classes depended on GUI classes.
What about using Observer/ Listener pattern? Your background tasks, launched by SwingWorker, can notify some other components when there is such need. #Xeon comment is pointing you in good direction.
Personal advice: start with some solution and then continuously refactor when code became not so readable.
btw. I hope you remember the old rule: Swing components should be accessed on the Event Dispatch Thread only ;)
You need to learn about concurrency design patterns, such as actors, futures, thread pools ect. Event driven means that you don't have blocking code, eg. rather than me waiting on you and constantly asking if you are finished with your task, you simply tell me once you are ready.
If you go the actor route you can wrap your gui class in a controller which is an actor which will process one message at a time. You need to be carefull with swing that you don't create event loops, as in event A triggers event B which triggers event A again and so on.
That's why an obserever pattern can be nice for displaying data.
But there is no silver bullet for concurrency unfortunately, the actor model is picking up, as well as futures, (take a look at akka), but it is essentially a difficult task so it will always be hard to get right.
Essentially I would say that the easiest approach is to make very strict rules on the sort of concurrency you are willing to accomodate, you need to think about the consequences of adding each bit of parallel functionality, and what effect it has. Then design your code based on that using a well established concurrency model.
What you want to do is the standard way most designers would want to do it, that is, have a background worker class which is independent of the GUI.
Creating a class, MySwingWorker, which extends SwingWorker and which calls your background classes is the standard approach. You may want to create one or more dialog classes to wrap your usage of MySwingWorkers, depending on the complexity of your application.

Register all interface instances to some global container

I need to shutdown alot of differently implemented threads which only have some Shutdown interface in common. I don't want to pass some global collection through the entire code and add newly created threads manually, because it is guaranteed to be forgotten somewhere and therefore is a bug hazzard.
Is there some neat way, maybe through reflection tricks, to grab all instances of some interface? Or is there alternativly some way to force newly created threads to register with the collection? I can only think of using some kind of super constructor and then passing the this reference, but this is extremly bad style.
This kind of task is like logging, some meta stuff that shouldn't live on the same level as the rest of the business logic.
Is there a standard shutdown registration pattern or some best practise?
P.S. All code fragments can be edited.
A brute force approach would be to list all running threads and simply use:
if(thread instanceof Shutdown) {
((Shutdown)thread).shutdown();
}
Of course there are more elegant approaches:
Use DI to inject the global thread container
Consider using ThreadFactory with some custom logic.
If you are open to some aspect oriented programming then you can accomplish this pretty easily using Aspect J.

What are the advantages of using Spring application event publishing?

I work on a web app that uses some Spring Application Event publishing and I was wondering what the advantages of it are? Why not just create a service call for everything that happens in the event handler's onApplicationEvent, and then call that service in place of publishing the event?
One of the advantages to using Spring's event publishing (observer pattern - http://en.wikipedia.org/wiki/Observer_pattern) is that the components are loosely coupled - there is no direct coupling between the publisher and the subscriber. Sure, they both have a dependency on the Spring Event API, but not on each other. This makes it possible to extend the application by adding/removing subscribers without affecting other subscribers (assuming that your subscribers don't depend on each other).
On the other hand, as you might have found, it can make debugging more tricky because it introduces a level of indirection between the source of an event and the overall outcome.
Yes, you can usually replace an event with a direct API call. Using Events are a good fit when:
you might in future need to take more than one independent action when the event occurs
the processing needs to be handed off to another thread to prevent blocking, e.g. sending an email (using a custom ApplicationEventMulticaster).
how the system handles the event, e.g. AuthorizationFailureEvent, does not depend on the outcome of the listeners.
You are writing a library, e.g. Spring Security, and direct API calls are not an option.
In answer to the part of the question that asks why not just create a service call; because someone else has already written the code, documented it and tested it.
Use Cases of Event-based Listener -
TDD becomes very handy(which in turn will eliminate bugs)
Best suited for Single Responsibility pattern (clean code) (Link for reference - https://www.youtube.com/watch?v=h8TWQM6fKNQ)

Java Swing design pattern for complex class interaction

I'm developing a java swing application that will have several subsystems. For all intents and purposes, let's assume that I am making an internet chat program with a random additional piece of functionality. That functionality will be... a scheduler where you can set a time and get a reminder at that time, as well as notify everyone on your friend list that you got a reminder.
It makes sense to organize this functionality into three classes: a GUI, a ChatManager, and a Scheduler. These classes would do the following:
GUI - Define all of the swing components and events
ChatManager - Create a chat connection, send and receive messages, manage friend list
Scheduler - Monitor system time, send notifications, store a file to remember events between sessions
For the program to work, each of these classes must be capable of communicating with the other two. The GUI needs to tell the ChatManager when to send a message and tell the Scheduler when to start monitoring. The ChatManager needs to display messages on the GUI when they're received, and finally, the Scheduler needs to both notify the GUI when it's finished, and send a status update or whatever to the ChatManager.
Of course, the classes as described here are all pretty simple, and it might not be a bad idea to just let them communicate with each other directly. However, for the sake of this question, let's assume the interactions are much more complex.
For example, let's say we can register a particular event with the scheduler instead of a particular time. When sending a message, I went to send it to the user, store it in a log file, create an event object and pass it to the scheduler, and handle any exceptions that might be thrown along the way.
When communication becomes this complex, it becomes difficult to maintain your code if communication with these classes can be happening in many different places. If I were to refactor the ChatManager, for example, I might also need to make significant chaneges to both the GUI and Scheduler (and whatever else, if I introduce something new). This makes the code difficult to maintain and makes us sleep-deprived programmers more likely to introduce bugs when making changes.
The solution that initially seemed to make the most sense is to use the mediator design pattern. The idea is that none of these three main classes are directly aware of each other, and instead, each is aware of a mediator class. The mediator class, in turn, defines methods that handle communication between the three classes. So, for example, the GUI would call the sendMessage() method in the mediator class, and the mediator would handle everything that needed to happen. Ultimately, this decouples the three main classes, and any changes to one of them would likely only result in changes to the mediator.
However, this introduces two main problems, which ultimately resulted in me coming here to seek feedback. They are as follows:
Problems
Many tasks will need to update the GUI, but the Mediator isn't aware of the components. - Suppose the user starts the program and enters their username/password and clicks login to login to the chat server. While logging in, you want to report the login process by displaying text on the login screen, such as "Connecting...", "Logging in...", or "Error". If you define the login method in the Mediator class, the only way to display these notifications is to create a public method in the GUI class that updates the correct JLabel. Eventually, the GUI class would need a very large amount of methods for updating its components, such as displaying a message from a particular user, updating your friend list when a user logs on/off, and so on. Also, you'd have to expect that these GUI updates could randomly happen at any time. Is that okay?
The Swing Event Dispatch Thread. You'll mostly be calling mediator methods from component ActionListeners, which execute on the EDT. However, you don't want to send messages or read/write files on the EDT or your GUI will become unresponsive. Thus, would it be a good idea to have a SingleThreadExecutor available in the mediator object, with every method in the mediator object defining a new runnable that it can submit to the executor thread? Also, updating GUI components has to occur on the EDT, but that Executor thread will be calling the methods to update the GUI components. Ergo, every public method in the GUI class would have to submit itself to the EDT for execution. Is that necessary?
To me, it seems like a lot of work to have a method in the GUI class to update every component that somehow communicates with the outside, with each of those methods having the additional overheard of checking if it's on the EDT, and adding itself to the EDT otherwise. In addition, every public method in the Mediator class would have to do something similar, either adding Runnable code to the Mediator thread or launching a worker thread.
Overall, it seems like it is almost as much work to maintain the application with the Mediator pattern than to maintain the application without it. So, in this example, what would you do different, if anything?
Your GUI classes will end up with many methods to keep it up to date and that is fine. If it worries you there is always the option of breaking up the GUI into sub GUIs each with a different functionality or a small set of related functionality. The number of methods will obviously not change, but it will be more organised, coherent and decoupled.
Instead of having every method in your GUI create a Runnable and use SwingUtilities.invokeLater to put that update on the EDT I'd advise you to try out another solution. For my personal projects I use The Swing Application Framework (JSR296) which has some convenient Task classes for launching background jobs and then the succeed method is automatically on the EDT thread. If you cannot use this you should try and create your own similar framework for background jobs.
Here, a partial answer to you design questions...
It looks like you want to have loose coupling between your components.
In your case, I would use the mediator as a message dispatcher to the GUI.
The ChatManager and the Scheduler would generate UpdateUIMessage.
And I would write my GUI that way
public class MyView {
public void handleUpdateMessage(final UpdateUIMessage msg){
Runnable doRun = new Runnable(){
public void run(){
handleMessageOnEventDispatcherThread(msg);
}
};
if(SwingUtilities.isEventDispatcherThread()){
doRun.run();
} else {
SwingUtilities.invokeLater(doRun);
}
}
}
So you have only one public method on your GUI, which handles all the EdT stuff.
If you want to have a loose coupling between the GUI and the other components (meaning : you do not want the GUI to know all the API of the other components), the GuiController could also publish ActionMessage (on a specific Thread?), which would be dispatched by the mediator to the other components.
Hope it helps.
Well, I will change the world you are working with. You have 3 classes and each of them is just observer of the chat-world. The MVC is the way how to deal with your problem. You had to create Model for your world, in this case chat program. This model will store data, chat queue, friend list and keep eye on consistency and notify everybody interested about changes. Also, there will be several observers which are interested in state of world and are reflecting its state to user and server. The GUI is bringing visualization to friends-list and message queue and reacts on their changes. The Scheduler is looking about changes in scheduled tasks and update model with their results. The ChatManager will be better doing its job in several classes like SessionManager, MessageDispatcher, MessageAcceptor etc. You have 3 classes with empty center. Create center and connect them together using this center and Observer Pattern. Then each class will deal only with one class and only with interesting events. One GUI class is bad idea. Divide to more subclasses representing logical group (view of model). This is the way how to conquer your UI.
You might want to look at a project that originally started as a MVC framework for Flex development. PureMVC has been ported to many programming languages meanwhile, including Java. Though it is only in a alpha status as of writing this!

Categories