I'm upgrading my python websocket game server to Java, (using Jetty for websockets), and recently started to learn about thread safety.
My challenge is, the game logic (gameRoom instance) runs on the main thread, but the server will be receiving player messages (eg. a message to join a game room), and notifying the game logic FROM ANOTHER THREAD. I originally (in python-when all was on the main thread) just processed the message right away, (eg. add a player on recieving a message). This can lead to problems with multiple threads, as the gameRoom thread might be adding a player at the same time, to the players array. (The players list ends up being shared during adding a player= not thread safe!)
What's the SIMPLEST way to handle recieving messages from a servlet running on it's own threads, and process these messages WITHOUT messing up the game running on the main thread(a different thread)? In my head, i'd imagine some kind of one-way buffer (eg. http://web.mit.edu/6.005/www/fa14/classes/20-queues-locks/message-passing/) to queue new messages to be processed ONLY by the gameRoom itself, during part of the logic. Or is there a way to avoid mulitple threads at all!? *Please give your thoughts, I'd love to hear from someone with more than my begginner level of thread knowledge. I greatly appreciate all tips/ advice :) *
I took the time to make a SIMPLE EXAMPLE showing what's going on (please ignore synax errors, i made it super short for your convinience :) ):
class ServerClass {
static GameRoomClass gameRoom;
static void main() {
//psuedocode start Jetty Server, this server runs in another thread, will call onServerMessage()
jettyServer.start();
jettyServer.onMessageCallback=(onServerMessage); //set message callback (pseudocode)
//create game room, run on main thread
gameRoom = GameRoomClass();
gameRoom.runGameRoom();
}
//when the server gets a message from a player,
//this will be called by the server from another thread, will affect the GameRoom
static void onServerMessage(Message theMessage) {
gameRoom.gotServerMessage();
}
}
//this runs game logic
class GameRoomClass {
ArrayList<E> players = new ArrayList<>();
public void runGameRoom() {
while (true) {
//move players, run logic...
//sometimes, may call addNewPlayer AS WELL
if(...){
addNewPlayer();
}
}
}
public gotServerMessage(){
//this will only be called by the 'Server' thread, but will enter 'addNewPlayer' method
//meaning it will access shared value players?
addNewPlayer()
}
public addNewPlayer(){
//this will be called by the server thread, on getting a message
//can ALSO be called by gameRoom itself
players.add(new PlayerObj());
}
}
class PlayerObj {
//a player in the game
}
The simplest and efficient way is to use one of thread-safe collection classes from java.util.concurrent package.
For the given case ConcurrentLinkedQueue seems to be a good start.
All,
I have appreciated many helpful answers on this site but I have found a need to post my first question (if you notice anything to be improved in my post let me know).
I have a modest sized Java program with GUI that is acting as a "middleman" and controller. On one end of the information flow it sends and receives data via an HTTP server. On the other it is interacting with an API where data is ultimately exchanging with a SmartCard. In the "middle" is the GUI, logging, and some other features.
There is also a feature (initiated via the GUI) to occasionally load an update to the SmartCard. Otherwise exchanges with the SmartCard are initiated over HTTP.
The problem is when switching between these 2 modes (communicating http to smartcard and then switching to loading the update or vice versa).
When I do that I have concluded I run into the problem of
CardException: Exclusive access established by another Thread
as thrown by sun.security.smartcardio
Searching the web shows the code that exception appears to come from is
void checkExclusive() throws CardException {
Thread t = exclusiveThread;
if (t == null) {
return;
}
if (t != Thread.currentThread()) {
throw new CardException("Exclusive access established by another Thread");
}
}
My first thought was I needed to instantiate the SmartCard API each time I need it (and then set it back to null) instead of once for the entire program like I had initially.
This works for the exchanges over http and I figure it is because each request to the handle() method is a new thread.
In the GUI the update is initiated by an ActionEvent which makes an instance of a CardUpdate. Inside that class then gets an instance of the SmartCard API.
I thought maybe I'd have better luck if when actionPerformed triggered I put the actions on a different, temporary, thread. So far, no.
The closest I got was using something like:
SwingWorker worker = new SwingWorker<ImageIcon[], Void>() {
as found at on Sun's website
Using that I could do an update and then go back to http exchanges but I couldn't do another update (per the one time use stipulation of SwingWorker)
I then tried making multiple SwingWorker as needed doing something like
private class GUICardUpdate extends SwingWorker<Integer, Void > {
but then I was back to my original problem. I have also tried to just do a simple additional thread off the GUI class in this fashion:
public class GUI extends javax.swing.JFrame implements ActionListener, Runnable
but this is no different.
Maybe I don't understand threads well enough or maybe I am overlooking something simple. Anyone have any ideas?
Thanks!
As far as I got you are using javax.smartcardio package (directly or indirectly) to work with your card. Some thread (created by you or by the framework you are probably using on top of javax.smartcardio) invoked beginExclusive() method on the Card instance to ensure exclusive access to the card.
The exclusive access is necessary as treatment of the data kept on the IC cards is state-depended, so the proper selection of data files and reading of their records requires the actions of application layer not to be interfered with actions of some other application or thread. For this purpose these three Card interface methods beginExclusive(), endExclusive() and checkExclusive() exist.
So you should check your(framework) code if it calls beginExclusive() and then doesn't call endExclusive().
I have to create an application having a GUI. my application has to work as a server. When it starts, it has to accept all the incoming connection and write the output in a JTextArea. my problem is where I have to create the ServerSocket ss = new ServerSocket(port_number) and the method ss.accept in the way I can accept connections. I tried to create in the main constructor of my gui but being ServerSocket anI/O request the gui stucks.some idea to resolve the solution?
I create in the constructor of my GUI:
SwingUtilities.invokeLater(new Runnable(){public void run(){connection();}});
where connection() is the method where I create the serversocket and accepts call
You should create a separate thread to wait/handle the network connections.
When a new connection comes in read the data and pass them to the EDT to update the GUI.
This way the GUI will be responsive.
You should read about MVC Pattern threads. If you Google there is an abundance of articles to study
UPDATE:
Your code here is wrong.
SwingUtilities.invokeLater(new Runnable(){public void run(){connection();}});
You are handling the connection from the EDT thread.
You should use this to update the GUI and not to call the network I/O code.
The IO logic must be in (at least one) separate background thread. Each time something must be printed to the text area from one of those background threads, they should do it using SwingUtilities.invokeLater(), to make sure that the Swing components are only accessed from the event dispatch thread.
That said, I don't think it's a very good idea to have a GUI for a server. Why don't you simply write in a log file, and use any text editor to see what the server received. Or write the GUI of the server as a client of this server?
i have written a standalone connect 4 game.
next i would like to be able to play it over network and also have a chat function.
connect 4 GUI (JFrame) holds -> connect 4 game model
i would like to implement connect 4 network GUI(JDialog) (here the user can choose to act as a server or client) that holds Network API. (server only serving a single connection)
and finally a Chat GUI (JDialog) to exchange messages.
my question is how do i implement inter class/GUI communication? when a network message is received it ought to be delivered to the right receiver (game / chat) also messages sent from chat / game transmitted to remote machine.
i have looked into inner classes but was told it is a bad idea to implement so much with in single class and i did not like this idea a lot either.
i have written another game battleships in C# and it uses delegates to accomplish this task but sadly im informed that delegates are not available in Java.
im a beginner and at the moment exploring options so im open to your guidance.
thank you.
There are two issues here.
First, you must remember that all GUI operation must be issued from the Swing's Event Dispatching Thread (EDT). So, if another thread (such as the thread listening to network messages) want to update the GUI it must use SwingUtilities.invokeLater as follows:
// Network thread
final Message msg = getMessage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// This code will be executed on the EDT
// it can access the msg variable because it is final
}
});
The second point is that of coordinating the GUI objects and networking objects. I think the best approach is to create two Mediator classes that will receive notifications from the networking object and "translate" them into appropriate action on the GUI object (and vice versa). These mediators will also make sure that GUI events are dispatched on the EDT, as explained above.
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!