I am trying to make an intro to a game with some strings that I want one to wait for another to pop up, and I don't directly want to use Thread.sleep() for it to wait, because I am not sure if that is the best option. Is there any other way to make something wait than making the thread sleep, or will I just have to make the thread sleep?
If this is a game you shouldn't use sleeps or timers.
Typically games have their own internal clock mechanism. This means you will try to render the frames as fast as possible. Your OnRender method will be invoked with the current time of the game. You can use this to determine if enough time has passed to go to the next screen.
This means you will be given a point in time A in frame 1. You'll be given the Delta or another point in time B in frame 2. You can determine how much time has passed by using the delta or calculating the delta yourself. This is a very efficient mechanism for timing situations and worked quite well when games were single threaded. The idea of any program is to never block for anything.
The reasons things typically block is due to I/O such as reading from disk, the network or putting data on the GPU. In your situation you can do everything without blocking.
Here is a decent page on this https://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step
There's a standard mechanism for this: Object.wait() and Object.notify() (with their overloads / variants). You simply wait for some event to occur in one thread, and some other thread is responsible for notifying you (or everyone, in case of notifyAll) of that occurrence.
You can also make use of the new Condition mechanism introduced in java.util.concurrent.
If you're making this in a game, why not try using something like Actions in libgdx? You just chain different actors together. Whenever a property like visibility or position reaches the value you want, you trigger the next action. Properties conditions are checked during each update loop of your game.
Or if its a swing app, use a timer to check these properties.
long t1=0,t2=0;
long nanoWaitTime=10000; //to wait at least 10000 nano-seconds
t1=System.nanoTime();
//start waiting
long count=0;
boolean releaseCpuResources=true;
while(Math.abs(t2-t1)<nanoWaitTime)
{
t2=System.nanoTime(); //needs maybe 1000 cycles of cpu to get this value.
//so this is like busy-wait
//and minimum step may be 1 micro-seconds or more
if(releaseCpuResources)
{
count++;
if(count>1000)Thread.sleep(1);//after too many iterations, cpu gets overwhelmed
//so Thread.sleep makes it better for large waiting
//times
//but precision is lost. Like uncertainity principle
//but in a quantized fashion
}
}
// here continue to work after waiting
The resolution or precision may not be what you want in for all cpus.
Related
I'm programming a game in Java and I limit the FPS to 60. I figured out 2 different ways to get the same result, but I'm wondering which of them is the better/cleaner way to do it. Or maybe you have a different idea.
while(System.nanoTime() - thisFrame < fps_limit);
or
Thread.sleep(sleepingTime);
My thinking is that the while loop effects the CPU more than Thread.sleep, am I right?
Thanks in advance for your help!
Dom
You have the following main options:
While loop - This will consume CPU cycles and often will actually stop the system because while you are looping, other threads cannot run (on a one-core machine).
Thread.sleep() - This can be effective but you need to remember that is not guaranteed to wait the specified time.
DelayQueue - More up-to-date. Better/accurate timing.
ScheduledThreadPoolExecutor - Still more up-to-date than DelayQueue. Uses a Thread Pool.
You're right, while both with achieve what you're trying to do, the while loop will keep the processor occupied, consuming CPU time.
In contrast, Thread.sleep() frees the processor for the amount of time mentioned.
So, Thread.sleep() is better.
Both the answers posted already are good - sleep is better than loop. However, you can go into much more detail about how to write a good loop. If you are interested, here is a great resource: http://www.java-gaming.org/index.php?topic=24220.0
It covers topics like variable timestep and interpolation, which can be used to make your graphics run extremely smoothly. This solves the issues Thread.sleep has with not being 100% accurate in its timing as well as preventing your graphics from appearing jerky if your game performs some calculation that takes some time.
What I would do (pseudo code).
//timepast since last loop in ms
timepast = 0
fpslimit = 60
finished = true;
//while the game is running
while(runnning)
{
timepast += timeSinceLastrun
if(timepast > 1second/fpslimit && finished)
{
finished = false
dostuff(timepast)
}
//sleep for the time of 1second/fpslimit - timepassed to avoid cpu blocking
Thread.sleep((1second/fpslimit) - timepast )
}
dostuff(deltatime)
{
//do stuff in the end after it finished set
//finished to true so dostuff can be called again
finished = true
timepast=0
}
In this way you can easily limit the fps with a variable and dont need to block other threads.
as OldCurmudgeon said thread.sleep dosnt block other threads in java and make processor time available.
Thread.sleep causes the current thread to suspend execution for a
specified period. This is an efficient means of making processor time
available to the other threads of an application or other applications
that might be running on a computer system
Also you can pass timepast to the dostuff method as a deltatime so the game runs the same on all devices (same speed).
I concur with #ayush - while loops are usually blocking functions, whereas threads are more like interrupt-driven or parallel programming functions. I'm a bit green on Java, but could you not setup a timer rather than sleeping?
Yeah it looks like Timer constructs, like in C++, are available. Check this out: Timer in Java Thread
You should use neither of them. Please take a look at the documentation for ScheduledThreadPoolExecutor
In particular you are looking at this function
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)
while loop will use CPU resource and it is good only if your avg.waiting time is very less and expecting precision.
Thread.sleep() is fine if no precision is expected as CPU priority will change after thread wakes up and it may or may not be scheduled immediately to run and it also should not to be used like this
while(! canContinue()) {
Thread.sleep(1000);
}
For the above case, alternative is these cases better to use wait()/notify() if you want to suspend the current thread and wait for another thread to process something and then notify the current thread to continue.
some references you can read,
http://tutorials.jenkov.com/java-concurrency/thread-signaling.html
http://www.jsresources.org/faq_performance.html#thread_sleep
The context in this case is creating a game loop that integrates with the model and updates the view once per frame. Listeners interface with the controller, controller updates the model, repaint() handles the view update from model (on an overridden paintComponent() on a JPanel).
Appropriate answers include "never", haha.
This is a question I would think there is a preferable answer to, so it shouldn't be in violation of the rules.
I'm asking this because the main game loop is a Runnable instance which I'm locking to 60FPS (roughly, at the moment. Few milliseconds of difference as the current render loop is very inexpensive and 1000 / 60 loses a millisecond or two each cycle). Not locking the frame rate via Thread.sleep() causes something like 2.3 billion frames per second (apparently), which understandably thrashes my CPU. Not a problem per say, more of an example why frame-locking is desirable.
However in every single answer I come across, every single comment, the majority of them say "why are you even touching Thread.sleep() you don't want the EDT to sleep". Which is understandable if you have flaws in your loop that cause non-responsiveness, but this isn't the case in the applications I've put together yet. I've read all of the associated Event Dispatch Thread documentation, how to use Swing Timers, etc. I've even used Timers myself, and SwingWorkers too (in one case to delegate icon loading to the background to prevent blockers on GUI instantiation).
Is there even a preferred method here? I haven't come across many / any standalone game solutions in Java that don't rely on libgdx.
Use Swing Timer when:
You don't want to throttle or control the time between updates. Swing Timer only guarantees "at least" duration (it will trigger AFTER a given delay) and the length of time in which the event is processed may effect the amount of time before the next update.
So, if you have a delay of 16ms (rough 60fps), your callback takes 20ms to process, the time between the first and second callback may actually be 36ms
You would also use a Swing Timer when you want to use the existing (passive) rendering system supplied by Swing
Swing Timer is relatively simple and easy to use, it triggers callbacks within the Event Dispatching Thread, making it easy to modify the state of the game and schedule an updates to the UI, this reduces possible thread race conditions (between the painting and the updating)
Use Thread#sleep when:
You want more control over the timing, producing variable delays. In order to do this, you will need to manage your own Thread
This approach is more suitable to more complex animations and when you are using a BufferStrategy to control the output.
The reason for this is, with a Thread approach, you run the risk of race conditions between your thread changing the state and the paint cycle painting it. Instead, you will need to take control of the paint process yourself, so you know that when you paint something, the state does not change while you do it.
Using this approach provides more flexibility and control to make decisions about when things get done (and how), but increases the complexity and your responsibility for doing things
Thread.sleep is almost certainly used in the implementation of javax.swing.Timer and java.util.Timer, but these days the only real use case of Thread.sleep is for creating a timeout on something, typically an I/O connection. I used this once at work way back for delaying updating the GUI after requesting the users messages until a certain amount of time past from the last message sent from the server. I also used it here
In your case, you should be using the swing timer for your game loop
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
Is tight looping in a program bad?
I have an application that has two threads for a game-physics simulator. An updateGame thread and a render thread. The render thread is throttled by causing the thread to sleep for some milliseconds (to achieve the frame-rate I want) and the updateGame thread (that updates my in game objects positions based off some physics equations) was previously throttled by a 10 millisecond sleep.
However, I recently unthrottled the updateGame thread and the simulation of my objects movement seems to be significantly more realistic now that I have taken out that 10ms sleep. Is it bad to hot loop or have a tight loop?
private class UpdateTask implements Runnable
{
private long previousTime = System.currentTimeMillis();
private long currentTime = previousTime;
private long elapsedTime;
public void run()
{
while(true)
{
currentTime = System.currentTimeMillis();
elapsedTime = (currentTime - previousTime); // elapsed time in seconds
updateGame(elapsedTime / 1000f);
try {
Thread.currentThread().sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
previousTime = currentTime;
}
}
}
In this example I'm just sleeping for 1ms (and from my understanding with how millisecond accuracy and the sleep function works this is probably more like 5-10ms. If I sleep for any more than this it starts to have impacts on the accuracy of my collision detection and physics model.
Is it a bad practice to have tight loops or loops with 1ms sleeps in them? Is there something else I should do instead?
I read a really great post about efficiently and effectively executing physics calculations loop: Fix Your Timestep!
When a game is running that is usually the main application that the user cares about so tight looping is not that big of a deal. What you really should do though schedule your updates. You should know how long -- at your target framerate -- that your frame has to execute. You should measure the time that your frame took and only sleep for the time that your frame took minus that known frame time. That way your system will lock into a frame rate and not vary with the amount of time that your frame takes to render.
Another thing is that I don't believe that Thread.sleep has a very good resolution, well over 5 milliseconds, you may want to look for a more accurate timer available for Java.
It's only "bad" if it has an adverse impact on something else in your system. Rather than sleeping for 1ms, you might block on a condition that warrants updating, with a minimum of 1ms. That way you'll always sleep for at least 1ms, and longer if there's nothing to do.
As Adam has pointed out in his answer, there may be an adverse impact on the performance of the system.
I've also tried making games in a very similar manner (having a rendering and motion calculations on separate threads) and I have found that not having the Thread.sleep will cause the Java application to take a very significant portion of the CPU time.
Another thing to consider is that the system timer itself. As you've mentioned, although the Thread.sleep method is takes in the number of milliseconds to sleep, but that precision is dependent (as noted in the API specifications) on the timer provided by the operating system. In the case of Windows NT-based operating systems, the timer resolution is 10 milliseconds. (See also: System.currentTimeMillis vs System.nanoTime)
Yes, it is true that having the Thread.sleep has the potential to decrease the performance of your application, but not having that can cause the system utilization by the application to skyrocket.
I would guess the decision comes down to whether the application should take up a significant portion of the system utilization, or to act nice and share the CPU time with the other applications running on the system.
Also consider laptop users, running a tight loop continuously will keep the CPU running hard, and this will chew through their battery (many flash games are guilty of this). Something to consider when deciding whether to throttle your loops or not.
The answer by joshperry is pretty much what you want, but there are also a few ways about it. If you are using multiple threads, you have to also deal with locking etc. Depending on your game architecture that may / may not be a big deal. For example, do you do lots of locking, is there a lot of message passing between threads etc. If you are a traditional game you usually have a single main loop - I have a queue of CMD objects (runnable if you like, but can also be more event bus like in nature) that are executed continuously until the queue is empty. The thread then waits until it is signaled that a new cmd is in the queue. For most games this is usually enough. So the question then becomes how / when are cmds added. I use a timer/scheduler (also note the comments about java time resolution) to add a cmd to the main loop at the required frame rate. This has the advantage of also being kind to laptops etc. On startup you can also then benchmark the system to see how fast it is running, and then set an appropriate frame rate (ie. start with a supported base, then work to a max). Benchmarking or using user specified performance hints (ie. amount of rendering detail) can then be used by each type of cmd (ie. the render scence cmd / event looks at the performance settings for detail etc). (note - cmds dont' have to be runnable, they can be more like an event bus with listeners that are invoked on the main thread).
Also if a task wants to then use multi-thread/core's the handler for the cmd (if its an event type model - i personally like the event model - its easier to access the shared state info without needing global singletons) can then spawn multiple tasks (say using an existing thread pool - so the cost of new threads are not hit every cmd) and then use a barrier type class to wait for all the tasks to complete. This method usually makes locking easier, as each cmd (or system) usually has different locking requirements. Thus you can implement just the locking for that system and not have to worry about locking between sub systems - ie. for physics you can lock on bundles of objects in the game area, and each forked thread in the thread pool then worries only about its objects ie. thread1 handles objects1 to 20, thread2 objects 21-40 etc (this is just to illustrate the concept of how each cmd can implement a custom locking algorithm that works best for what it is doing, without having to worry about what other sub systems are doing with shared state data).
The important thing is to look at how and why you are using threads and locking etc.
For a game, probably not. Just make sure your game pauses when the switches tasks.
You would actually want to use Thread.yield() in this case. It is possible that one thread will run continuously, and not allow any other threads time to execute. Placing a yield call at the end of each iteration gives the scheduler a hint that it is time to allow other threads to run as well.