I have a client/server question that i am trying to figure out the best solution for.
If a client ever gets disconnected from the server, for any reason, i would like a way for the input output thread to alert the gui thread that something went wrong, and thus have the gui thread print an error and gracefully handle it (probably drop back out to the login gui). After the initial gui thread is created, the client could change to any number of guis, depending on what he is doing, so I am thinking i need a way to dynamically see what gui is currently being run.
The way that i was thinking of doing this so far:
1) Create an object that creates and shows every gui. So instead of calling invokeLater...SomeGui.CreateAndShoGui()... we would have this object be responsible for doing that, ie GuiObject.showSomeGui();
2) Have each gui implement an interface, which will insure there is a method that, when called, will gracefully shutdown this gui when we have lost connection to the server.
3) Have a thread that monitors the IO thread and the gui object. If something goes wrong on the IO thread, the IO thread will close down and notify the monitoring thread that we have lost connection the server. The monitoring thread could then alert any open guis (from the gui object) that we have lost connection and that it needs to shut down.
I have just started thinking about this, and so far this is the best solution i have come up with. Does this seem like a reasonable solution that wont add too much complexity to the code? Or can anyone recommend a solution that would be simpler for people reading the code to understand?
Thanks
EDIT:
The other option i am toying with is having an object on the IO thread, that also gets passed to each new gui as it is opened. This object will give the currently opened guis reference back to the io thread, so that the io thread can alert it if something goes wrong. I am leaning against this solution though, because it seems like it would be easier to read if you had one object that was dedicated to get this working (like the above solution), instead of passing some obscure object to each gui.
Let me just go through each of your ideas:
1) Bad idea - you are tying your whole application together through a single object. This makes maintainability difficult and is the antithesis of modularity.
2) This is the way to go IMHO. Since it seems that each gui has unique logic in a failure scenario then it stands to reason that the object that best understands what to do would be the gui object itself.
Another version of this idea would be to create an adapter for each gui to put this failure logic into. The advantage would be you have one less dependency between your application framework and your gui. The disadvantage is that this is an extra layer of complexity. If your gui is already pretty coupled to your application then I would choose the interface method. If you want to reuse your guis in another application then the adapter way could help facilitate that.
3) This complements #2 nicely. So let me get this straight - you would have 3 threads: the IO thread, the monitor thread, and the UI thread. I don't know if you need the monitor thread. From what you were saying the IO thread would be able to detect a connection problem by itself (probably because some form of IOException was caught). When a connection problem is discovered the IO thread is not busy since it is just going to shut itself down soon so it might as well just have the responsibility of notifying the guis that there was a problem. The guis should have their interface method called on the UI thread anyways so the IO thread is just calling a bunch of invokeLater() calls (or asyncExec() calls for SWT) and then the IO thread can just shut itself down.
4) (Your Edit) You are basically describing the Visitor pattern. I do not think this is a good solution because the call is from the IO thread to the gui and not the other way around. I am not sure how passing a visitor object around will help in this case.
One final thought. If you make your interface generic (not gui specific) then you can apply this pattern to other resources. For instance you may want to flush your user credentials when you lose connection (since you talked about going to the login screen again). That isn't really gui logic and should not be done from a gui class.
Edit: I would use an event model. Let's say you create a interface like this:
public interface ConnectionFailureListener {
void handleConnectionFailure(); // Add an event object if you need it
}
You could then have registration methods in some object (maybe the Runnable for the IO thread or somewhere else that is convenient for you). These methods would be pretty standard:
public void addConnectionFailureListener(ConnectionFailureListener l) {}
public void removeConnectionFailureListener(ConnectionFailureListener l) {}
When you show a gui on the screen you would add it to your registration object and when you close the gui you would remove it from the registration object. You can add other types of objects as needed - for example when you log in you can add a listener for your credential system and remove it again when log out is processed.
This way when you have a failure condition you simply loop through the currently registered listeners and the listener does its thing.
Related
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
I am coding as part of a project which uses multithreading and I'm trying to find ways to detect thread mistakes in my code.
Are there some existing tools I could use to help me do this?
For example-
an assert that my method is being called by the correct thread
or
some kind of static checking with annotations, similar to #Nullable and #NotNull, to detect when my code calls a method from the wrong thread.
Although the project is multithreaded, there is almost no synchronisation required because the different threads don't access the same objects, they have their own instances.
Broadly speaking, there are four threads running at once
Server thread = maintains the state of the game for one or more
clients
Client thread = processes user input, maintains a local
copy/cache of server data for rendering
NetworkMessage thread = processes incoming/outgoing messages
between server and client
Render thread = processes the local data into rendering information for the
graphics card
The classes are sometimes intended for only one of the threads (for example user input polling is client-only), sometimes they are for multiple threads (eg the calculated movement of a projectile uses the same code on both client and server simultaneously to reduce perceived lag). Several times I've called a method from the wrong thread, leading to subtle and unrepeatable bugs and very nearly serious monitor screen damage (from my fist)
What I have thought of so far is something like this:
public void myMethodThatAssumesClientThreadOnly() {
assert checkThread(CLIENT);
// can now happily call other client-thread code without fear
}
but I would prefer something with static checking similar to #Nullable
eg
#Thread(CLIENT)
void myClientMethod() {
//client-only stuff here
}
#Thread(SERVER)
void myServerMethod() {
//server-only stuff here
}
#Thread(CLIENT + SERVER)
void myClientAndMethod() {
myClientMethod(); // error- server thread might call client method
}
Unfortunately, being an annotation noob, I have no clue whether this is easy or actually very hard.
Any pointers? I can't imagine I'm the first one to look for something like this.
TGG
The Checker Framework enables the creation of compile-time static checkers that verify program correctness. Its GUI Effect Checker is similar to what you want. Here is an abridged excerpt from its manual:
One of the most prevalent GUI-related bugs is invalid UI update or invalid thread access: accessing the UI directly from a background thread.
If a background thread accesses a UI element such as a JPanel (by calling a JPanel method or reading/writing a field of JPanel), the GUI framework raises an exception that terminates the program.
It is difficult for a programmer to remember which methods may be called on which thread(s). The GUI Effect Checker solves this problem. The programmer annotates each method to indicate whether:
It accesses no UI elements (and may run on any thread).
It may access UI elements (and must run on the UI thread).
The GUI Effect Checker statically enforces that UI methods are only called from the correct thread.
The GUI Effect Checker is tuned to detect and prevent GUI threading errors, whereas you are concerned about client-server threading errors. However, the principles are the same and you should be able to adapt the GUI Effect Checker to your needs with relatively few changes.
There is a paper that discusses case studies using the GUI Effect Checker.
An alternative is to adapt a bug finder for finding errors in multithreaded applications. Unlike the GUI Effect Checker, it does not give a guarantee that there are no threading bugs. However, it is effective in practice, and it does not require you to write any annotations in your program.
Finally, the Checker Framework also contains a Lock Checker that ensures correct synchronization. That helps to prevent concurrency errors, though it's orthogonal to your chief concerns about thread safety.
This will assert that method foobar() is called by the correct thread...
SomeType foobar(...) {
assert(Thread.currentThread() == theCorrectThread);
...
}
...If, somewhere in your code prior to the first foobar() call you have set
Thread theCorrectThread = new Thread(...);
but I would prefer something with static checking similar to #Nullable
I know very little about annotations myself. I know that they can be used to attach meta-information to compiled classes, and I know that the program can obtain that information at run-time by calling methods of the Class object, but if there's any way an annotation can define compile-time behavior, that's beyond my ken.
Probably a moot point anyway. When the compiler is processing a .java file, there is no way for it to tell what thread or threads might possibly execute the code that it contains.
I'm fairly new to java and I was creating a program which would run indefinitely. Currently, the way I have the program set up is calling a certain method which would perform a task then call another method in the same class, this method would perform a task then call the initial method. This process would repeat indefinitely until I stop the compiler.
My problem is when I try to create a GUI to make my program more user friendly, once I press the initial start button this infinite loop will not allow me to perform any other actions -- including stopping the program.
There has to be another way to do this?
I apologize if this method is extremely sloppy, I sort of taught myself java from videos and looking at other programs and don't entirely understand it yet.
You'll need to run your task in a new thread, and have your GUI stuff in another thread.
Actually, if you keep working on this problem, you'll eventually invent event driven programming. Lots of GUI based software, like Android, use this paradigm.
There are several solutions. The first that comes to mind is that you could put whatever method needs to run forever in its own thread, and have a different thread listen for user input. This might introduce difficulties in getting the threads to interact with each other, but it would allow you to do this.
Alternatively, add a method that checks for user input and handles it inside the infinite loop of your program. something like below
while(true){
//do stuff
checkForUserInput();
//do other stuff
}
To solve this problem, you need to run your UI in another thread.
Many programs are based on an infinite loop (servers that keep waiting for a new user to connect for example) and your problem isn't there.
Managing the CPU time (or the core) allocated to your infinite loop and the one allocated to take care of your UI interactions is the job of the operating system, not yours : that's why your UI should run in a separate thread than your actual code.
Depending on the GUI library (Swing, ...) you're using there may be different ways to do it and the way to implement it is well answered on Stack Overflow
I have a GUI and the GUI is starting another thread (Java). This thread is starting a class which is crawling many websites. Now I want to show in the GUI how many websites are crawled and how many are left.
I wonder what's the best solution for that.
First idea was to start a timer in the GUI and periodically ask the crawler how many is left. But I guess this is quite dirty...
Then one could pass the GUI to the crawler and it is calling a GUI method every time the count of ready websites changes. But I don't think that's much better?
What is the best way to do something like that?
It depends.
Ask the crawler how much work it is done isn't a bad idea. The benefit is you can actually control when an update occurs and can balance out the load.
The downside is that the information may go stale very quickly and you may never get accurate results, as by the time you've read the values, the crawler may have already changed them.
You could have the crawler provide a call back interface, which the GUI registers to and when the crawler updates it's states, calls back to the GUI.
The problem here is the UI may become swamped with results, causing to lag as it tries to keep up. Equally, while the crawler is firing these notifications, it isn't doing it's work...
(Assuming Swing)
In either case, you need to make sure that any ideas you make to the UI are made from within the Event Dispatching Thread. This means if you use the callback method, the updates coming back will come from the crawlers thread context. You will need to resync these with the EDT.
In this case you could simply use a SwingWorker which provides mechanisms for syncing updates back to the EDT for you.
Check out Concurrency in Swing for more details
register a callback function to your thread. when your data is dirty, invoke this callback function to notify GUI thread to update. don't forget to use synchronization.
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!