Suppose I have a nametag, which is UI component in GUI program.
The nametag will constantly change its text based on the data.
If the user change his/her name data, then he/she will see the change in nametag.
For this task, my code looks like this:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
String name = data.getName();
nametag.setText(name);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Since the reaction time of 0.1s seems instant to people, I included Thread.sleep(100) for computer to take a break.
However, I am not sure if that helps the computer in terms of energy usage or something. Is sleep method in this case complete waste of time? No benefit at all?
Thread.Sleep has been used for many things it shouldn’t be used for.
Here’s a list of the common mistakes:
The thread needs to wait for another thread to complete
In this case no value, other than infinite, passed to Thread.Sleep will be correct. You simply don’t know when the other thread will complete using this method. If the thread completed after Sleep returned you’ll likely have synchronization problems. If the other thread completed before Sleep returned the thread was needlessly blocked for an amount of time rendering the benefits of multithreading limited or moot. In the control circumstances where you’ve tested this it may seem like it always works; it just takes a busy program to cause it to faile: a defrag program, a sudden influx of network traffic, a network hiccup, etc.
The thread needs perform logic every n milliseconds
As noted earlier, Sleep means relinquish control. When your thread gets control again isn’t up to the thread; so it can’t be used for periodic logic.
We don’t know why Thread.Sleep is required; but if we take it out the application stops working
This is flawed logic because the application still doesn’t work with Thread.Sleep. This is really just spackling over the problem on that particular computer. The original problem is likely a timing/synchronization issue, ignoring it by hiding it with Thread.Sleep is only going to delay the problem and make it occur in random, hard to reproduce ways.
Source: http://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/
This doesn't answer your direct question, but it does help address an XY Problem component of your question:
It looks like you're listening for object state changes by polling: by constantly testing an object to see what its state is and whether it's changed, and this is a bad idea, especially when coding for an event-driven GUI. Much better to use an observer pattern and be notified of state changes when or if they occur. That is how the Swing GUI library itself was written, and you should strongly consider emulating this.
Some ways to be notified of changes are to use component event listeners which can listen for changes to Swing components, such as ActionListeners, ChangeListeners, ItemListeners, and the like. Another way when listening to non Swing component items is to use SwingPropertyChangeSupport and PropertyChangeListeners and in this way to create "bound" properties of your class. This is often used for non-GUI model classes.
Related
Long story short; I've written a program that contains an infinite loop, in which a function is run continuously, and must run as quickly as is possible.
However, whilst this function completes in a microsecond time scale, I need to spawn another thread that will take considerably longer to run, but it must not affect the previous thread.
Hopefully this example will help explain things:
while (updateGUI == true) { //So, forever until terminated
final String tableContents = parser.readTable(location, header);
if (tableContents.length() == 0) {//No table there, nothing to do
} else {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
//updateTable updates a JTable
updateTable(tableContents, TableModel);
TableColumnModel tcm = guiTable.getColumnModel();
}
});
}
***New thread is needed here!
}
So what I need is for the readTable function to run an infinite number of times, however I then need to start a second thread that will also run an infinite number of times, however it will take milliseconds/seconds to complete, as it has to perform some file I/O and can take a bit of time to complete.
I've played around with extending the Thread class, and using the Executors.newCacheThreadPool to try spawning a new thread. However, anything I do causes the readTable function to slow down, and results in the table not being updated correctly, as it cannot read the data fast enough.
Chances are I need to redesign the way this loop runs, or possible just start two new threads and put the infinite looping within them instead.
The reason for it being designed this way was due to the fact that once the updateTable function runs, it returns a string that is used to update a JTable, which (as far as I know), must be done on Java's Main Dispatch Thread, as that is where the GUI's table was created.
If anyone has any suggestions I'd greatly appreciate them.
Thanks
As you are updating a JTable, SwingWorker will be convenient. In this case, one worker can coexist with another, as suggested here.
You have to be very careful to avoid overloading your machine. You long running task need to be made independent of you thread which must be fast. You also need to put a cap on how many of these are running at once. I would put a cap of one to start with.
Also you screen can only update so fast, and you can only see the screen updating so fast. I would limit the number of updates per second to 20 to start with.
BTW Setting the priority only helps if your machine is overloaded. Your goal should be to ensure it is not overloaded in the first place and then the priority shouldn't matter.
It's very hard to guess what's going on here, but you said "results in the table not being updated correctly, as it cannot read the data fast enough". If you really mean the correctness of the code is affected by the timing not being fast enough, then your code is not thread safe and you need to use proper synchronization.
Correctness must not depend on timing, as timing of thread execution is not deterministic on standard JVMs.
Also, do not fiddle with thread priorities. Unless you are a concurrency guru trying to do something very unusual, you don't need to do this and it may make things confusing and/or break.
So if you want your "infinite" looping thread to have max priority, why are you setting priority to MAX for EDT insted of you "most precious one"?
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
//updateTable updates a JTable
updateTable(tableContents, TableModel);
TableColumnModel tcm = guiTable.getColumnModel();
In this piece of code current thread will be and EDT, or EDT spawned one. Why not moving that line before intering whileloop?
I'm making a programming game where the player can program their allies' behavior. The player writes the body of the decide() function for a given ally, which can be filled out with any java code but has to return an action. I would like to give each ally a set, restricted amount of computation per tick so 1) adding more entities doesn't slow down the game too much, and 2) The time an entity spends computing is reflected in game, so if an ally spends more time "thinking" it will act less often. My inspiration for how this should work is Battlecode, which gives units a set amount of bytecode per turn, then just pauses the computation and makes the programmer deal with noticing when things have changed.
My question is how I can pause and resume an entity which is executing the decision function in a thread. I understand the 'proper' way to do this is to set a flag telling the thread to pause and have it check occasionally, but since I can't force the player to check for a flag within the decide() function, I'm not sure how to pause the thread. The entities are only looking at a fixed representation of the world and just have to return an enum value, so I don't think they should have locks on anything, but I'm hoping there's a better way to do this than using the deprecated thread pausing methods. I'm open to changing how the player has to write code, but I can't think of a way to do it while still hiding the pause flag checks from the user without making writing the decision loop confusing and onerous. There must be some way to do this, since Battlecode does it, but I'm at a loss searching online for details as to how.
If you want to 'pause' the current thread, java.util.concurrent.locks.LockSupport may helps you. If you want to pause other threads, I thinks it's not in the scope of java design, you can only interrupt another thread, or set a flag, not pause.
You can't "pause a thread", and you can't expect players to abide by your request to "play nice" and check for flags etc. You can interrupt another thread, but the code running in the thread can easily recover from this. So, you need a way for the controlling thread to retain control.
Instead of worrying about what threads are doing, you could:
give the player threads a maximum time to return the action, and if they don't return in time, execute a "default action"
keep a record of how much time they spent calculating and call them more often is they use less time etc
Most of these types of concerns are catered for by java.util.concurrent library. Check out:
ExecutorService
Executors for creating handy instances of ExecutorService
Callable for what the players will implement
Future for getting the result, especially Future.get(timeout) for limiting the time the thread has to return a result
I'm writing a game in which a thread - GameThread - loops forever, updating all my sprites, rendering them, and then sleeping for some time before doing it all again. I also have a custom-made Event handler which deals with key presses etc.
This all works fine in most cases. However I have a problem if an event is thrown while GameThread is rendering. On rare occasions, the handler that deals with the event may make a concurrent change to what needs to be rendered affecting the results of the GameThread rendering.
To avoid this, I want the event handler to pause the GameThread immediately, handle the event, then resume GameThread.
The suspend() / resume() methods suit my needs, but they were deprecated. In my case, however, as there is little chance of a deadlock, is it safe to use them regardless?
If no, what other alternatives do I have that don't have a huge amount of overhead?
I have seen a suggestion of requesting a thread to pause by setting a flag in the Thread to be paused. In my case, however, I don't see that as a viable option since the GameThread loop may take a while during an iteration through the loop. I won't be able to check the flag until I'm done with the loop and by then it is too late.
I need immediate pausing, or else the user will notice a delay in the event handling.
If you want to synchronize access to resources, use a ReentrantLock:
ReentrantLock sync = new ReentrantLock();
You'd have to pass that lock to each runnable where you want to access the shared data.
Then in each place you're accessing the resource in question, you would use that shared lock object, and obtain and release the lock (ie, your critical sections):
sync.lock();
try {
// critical section code here
}
finally {
sync.unlock();
}
This is pretty standard concurrent programming in java. Keep in mind "lock" is a blocking method, so you might want to use "tryLock" instead, which allows you to try and acquire the lock, but returns a boolean as to whether or not you actually got the lock:
if (sync.tryLock()) {
try {
//critical section
}
finally {
sync.unlock();
}
}
There's a version of "tryLock" which will wait a given amount of time, before it will give up trying to acquire the lock and return a false value.
Usually, you would do some thread synchronization:
http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
This would let you do one of the two things you are doing: either render in the game rendering thread or do the changes based on your events.
The problem you are facing seems to be that your rendering code is taking too long for you to actually have a smooth experience (i.e. a lot of events can pile up for processing while you are rendering something). In that case, you should make your rendering out of independent pieces that can finish quickly and synchronize on them.
Without any code I cannot give you a specific advice, however in general it would look something like this:
List<Shape> shapesToRender;
Object lockObject = new Object(); // Note this must be somehow shared between two threads
// Your rendering thread method
public void renderForever() {
while(true) {
for(Shape shape: shapesToRender) {
synchronized(lockObject) {
render(shape);
}
}
}
}
// One of your event handlers
public void handleEvent(Event event) {
synchronized(lockObject) {
// Process event somehow, e.g. change the color of some of the shapes
event.getShape().setColor(Color.RED);
}
}
With the above, either:
You will be rendering one shape (and all your event handlers will be waiting for that to finish), or
Some of your event handlers will be doing something (and your rendering thread will be waiting for that to finish)
You should look at this Java trail in more depth:
http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
as there are other solutions, e.g. using lock objects:
http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html
or concurrent collections:
http://docs.oracle.com/javase/tutorial/essential/concurrency/collections.html
that, depending on your problem, might be easier and, most importantly, very well tested solutions that would allow you to do something in a standard way, thus avoiding all the pitfalls that you can get into when rolling out custom threading code.
Hope this helps.
The suspend() / resume() methods suit my needs, but they were deprecated. In my case, however, as there is little chance of a deadlock, is it safe to use them regardless?
Obviously, if there is ZERO chance of a deadlock then it is safe. But there are all sorts of unexpected ways to get a deadlock. For instance, you could happen to pause a thread while it is initializing a class ... and that would deadlock any other thread trying to refer to a static field of that class. (This is a consequence of a specified behaviour of the JVM. There are other places where the locking / synchronization that goes on under the hood is not specified. Fair enough. It doesn't need to be ... unless you are contemplating using these deprecated methods.)
So, the reality is that it is really difficult to determine (prove) if it is actually safe. And if you can't determine this, then it is a potentially risky thing to do. That's WHY the methods are deprecated.
(Strictly speaking, this is not a deadlock. A deadlock is when the threads can never proceed. In this case, the other threads can proceed if you can resume the paused thread.)
I am writing a simple top down space game, and am extending it to allow play over a network with multiple players. I've done a fair bit of reading, but this is the first time I've done this and I'd appreciate some advice on choosing a sensible design.
My GUI is written using Swing. 30 times a second, a timer fires, and repaints my GUI according to data in a gameWorld object in memory (essentially a list of ships & projectiles with positions, etc). Physics updates of the gameWorld are also carried out using this timer. Thus, for the single player implementation, everything happens on the EDT, and this works fine.
Now, I have separate thread dealing with incoming packets from other players. I would like to update the data in my gameWorld object based on what these packets contain. My question is, should I use invokeLater to make these changes, or should I use locks to avoid concurrency problems?
To illustrate what I mean:
runMethodOfInputThread() {
while(takingInput) {
data = receiveAndInterpretIncomingPacket(); // blocks
SwingUtilities.invokeLater(new Runnable() {
public void run() {
gameWorld.updateWithNewGameInfo(data);
}
});
}
}
vs
runMethodOfInputThread() {
while(takingInput) {
data = receiveAndInterpretIncomingPacket(); // blocks
synchronize (gameWorldLock) {
gameWorld.updateWithNewGameInfo(data);
}
}
}
The latter would also require using similar synchronize blocks wherever the EDT accesses the gameWorld, so it seems to me that using invokeLater would be simpler to implement. But am I right in thinking both approaches would work? Are there any other significant pros/cons to bear in mind?
Thanks,
Jeremy
Well, first of all you don not need to choose only one method. You can use locks to make you data structure thread-safe "just to be sure" (since your application is already multithreaded), and use invokeLater to actually apply changes only in EDT -- and in this case JIT likely to optimize you locks down, close to 0.
Next, from my point of view invokeLater is rather preferred way: if you can way around dealing with multi-threaded -- you should use the way, just because multithreading is hard and rich of possible errors.
But applying changes via invokeLater() will put additional pressure on EDT, so, if changes come with high rate you can observe GUI degradation. Also, if gameWorld.updateWithNewGameInfo(data) is havy method taking observable time to complete, it can makes you GUI even freeze. Also, invokeLater puts your task at the tail of event queue, so it'll be done after all events currently in queue. It may -- in some cases -- cause delays in applying changes, which can makes you game less user-friendly. It may, or may not be your case, but you'll should keep it in mind
As for general rule -- not use EDT for any time consuming task. As far, as I understand, network packet parsing is already in seperate thread in your application. Applying changes can (and should) be done in separate thread too, if it is time consuming.
Pros for approach 1:
Minimized complexity
Stability
By restricting access to the 'gameWorld' variable to the EDT thread, locking mechanisms are not required. Concurrent programming is complex and requires the programmer(s) to be vigilant throughout the source base when accessing objects shared amongst threads. It is possible for
a programmer to forget to synchronize in certain instances, leading to compromised game states or program failure.
Pros for approach 2:
Scalability
Performance
Minimizing the processing done on the EDT thread ensures that the games interface and display will remain responsive to the user. Approach 1 may work for now, but later revisions of your game will not be able to scale to a more advanced interface if the EDT thread is busy doing non-ui processing.
Not the second one. You want to have as little as possible running in the EDT. If you are waiting for a lock in the EDT, it's as bad as running all the other code (on the other side of the lock) directly in the EDT since the EDT has to wait for everything else to finish.
Also, it seems that your whole game is running on the EDT. That's bad practice. You should split your code using the model-view-controller pattern. I understand your game is small and can run in the EDT, but you should probably not get into the habit.
You should have your game logic running from a timer thread (java.util.concurrent.ScheduledThreadPoolExecutor) and at the end of every period you "send" your data to the EDT and repaint with invokeLater.
You should also have some separate thread that reads the socket and that thread should write to objects that share locks with the objects you are using in the timer game thread.
My suggestion is as follows
push all loaded data from different users (thread) to a queue
use another thread to read from that queue and update UI from EDT
It should avoid your concurrency issue. How it can be achived
runMethodOfInputThread() {
while(takingInput) {
data = receiveAndInterpretIncomingPacket(); // blocks
blockingQueue.add(data);
}
}
runMethodOfUPdateUIThread() {
while(updatingUI) {
data = blockingQueue.take();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
gameWorld.updateWithNewGameInfo(data);
}
});
}
}
After having some trouble with setting up a thread to start my MIDI sequencer I decided to simply remove it, although it would slow my UI down I would be able to use it correctly.
What I noticed however was that even when playing the Sequencer the UI was very much active, even if it was playing around 500 notes the UI worked perfectly fine.
Now I know that in C# if you are doing something intensive it is advisable to load it on a new Thread as it will free the UI. Is it the same principle in Java, it's really confused me. If so can someone explain how the UI is not being blocked?
Thanks
Edit:
The following code actually plays the Sequence
public static boolean Play() {
if(!_sequencer.isRunning()) {
try {
_sequencer.setSequence(_sequence);
_sequencer.start();
return true;
} catch (Exception e) {
Logger.Add(e.getMessage());
}
}
return false;
//Already running
}
Yes, it is the same theory. Only the Event Thread can modify the UI, and thus if you are doing anything on that thread, then you are preventing other events from working on the UI.
It may be easier to think about the Event Thread as a queue:
Show Form
Click Button
Do your work (Action)
Reset focus of Button
Update Progress Bar
Et cetera
If #3 takes long, then it may mean that your form will appear locked up. Obviously it completely depends on your definition of long. In general, it's better to work off of the Event Thread rather than on it.
It's definitely the same principal. Generally speaking you want to only do minimal work with the UI thread. If it ends up taking any significant time, it can cause the UI to be unresponsive and you can get a "Not Responding" error. You want to keep the UI thread as free as possible so it can respond to user interaction.
If your application has a graphical user interface, it's advised that you perform expensive calculations on a new Thread to keep your graphics from freezing. You can either create a SwingWorker, or use the Callable/Future idiom.
Yes, you're right. Read Threads and Swing for more info.