Games in Java: Timing with possibility of pause/resume - java

currently i am developing a set of simple games for Java (with JavaFX2 as GUI). Just now i ran into the need of "pausable timers". Does anybody know a library for game timing that enables me to pause timers without implementing it myself? For implementing countdowns and fixed rate things.
I need to:
- schedule TimerTasks at a specific rate (thats already in the JDK)
- schedule TimerTasks with a fixed delay
- pause the timer
- resume the timers so that everything starts of where i paused it.
It would be really cool if somebody knew something like that.
Thanks.

I'm pretty certain there's nothing in the JDK that does this, and I don't know of any libraries to do it.
However, I think instead of trying to pause and resume some sort of timer, you should simply wrap anything that relies on executing periodically in a condition so that it only executes when not paused. If the rate at which tasks are scheduled is sufficiently fast, the difference should not be noticeable for the user. For example:
public abstract class PausableTask extends TimerTask {
private final AtomicBoolean isPaused;
public PausableTask(AtomicBoolean flag) {
isPaused = flag;
}
#Override public final void run() {
if (!isPaused.get()) go();
}
public abstract void go();
}
Then you could have one global paused flag, and any time you are using TimerTasks, use this class instead, passing the global flag. You could even make the flag a public static variable of the PausableTask class.
Maybe this approach isn't even applicable to your game and you have some reason to need more accurate pausing, but if not, hopefully this helps!

You may want to take a a look at Quartz Standby method -
http://www.quartz-scheduler.org/docs/api/1.8.1/org/quartz/Scheduler.html#standby()
From the API -
Temporarily halts the Scheduler's firing of Triggers.
When start() is called (to bring the scheduler out of stand-by mode), trigger misfire instructions will NOT be applied during the execution of the start() method - any misfires will be detected immediately afterward (by the JobStore's normal process).
The scheduler is not destroyed, and can be re-started at any time.
Quartz is a very good framework which you can plugin to your application. It is also highly customizable so you can utilize it.

Related

What is the difference between Timer and Runnable?

I would like to know what exactly the difference is between these two classes, and when should I use each.
I am asking this because I am wondering about this sample code:
mStatusChecker = new Runnable() {
#Override
public void run() {
invalidate();
mHandler.postDelayed(mStatuschecker, (long) increment * 1000);
}
};
If I put the mHandler.postDelayed line of code before invalidate(), the Runnable is executed at almost double the speed. I am wondering if a Timer could be used instead to fix this problem.
Timer is a facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
It's better to user Timer functionality if you need timer functionality like task needing to be run at regular intervals.
Java java.util.Timer is a utility class that can be used to schedule a
thread to be executed at certain time in future. Java Timer class can
be used to schedule a task to be run one-time or to be run at regular
intervals. Java Timer class is thread safe and multiple threads can
share a single Timer object without need for external synchronization.
https://www.journaldev.com/1050/java-timer-timertask-example
Timer is not an Android class, it's a Java SDK class included in the Android SDK for compatibility with legacy code. It does not play well with the Android component lifecycle and requires extra code to interact with the UI. In short, do not use Timer on Android.

GWT: Timer and Scheduler Classes

I have read this page over several times, and am just not seeing some of the inherent differences between GWT's Timer and Scheduler classes. I'm looking for the use cases and applicability of each of the following:
Timer, Timer::schedule and Timer::scheduleRepeating
Scheduler::scheduleDeferred
Scheduler::scheduleIncremental
IncrementalCommand
DeferredCommand
These all appear to be doing the same thing, more or less, and it feels like you can accomplish the same objectives with all of them. Is this just GWT's way a providing multiple ways of doing the same thing? If not, please help me understand when and where each is appropriately used.
Use Scheduler when you need a browser to complete whatever it is currently doing before you tell it to do something else. For example:
myDialogBox.show();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
#Override
public void execute() {
myTextBox.setFocus();
}
});
In this example, focus will not be set until the browser completes rendering of the dialog, so you tell the program to wait until the browser is ready.
Use Timer if you want some action to happen after a specified period of time. For example:
notificationPanel.show();
Timer timer = new Timer() {
#Override
public void run() {
notificationPanel.hide();
}
};
timer.schedule(10000);
This code will show notificationPanel, and then it will hide it after 10 seconds.
As the JavaDoc says, DeferredCommand is deprecated in favor of Scheduler.
The problem with DeferredCommand and IncrementalCommand is that they have a static state (which makes it hard to use reliably in tests). Moreover, their (static) methods make JSNI calls which forces you to use a GWTTestCase to test your code (static methods aren't –easily– mockable). Static methods also make it impossible to wrap them (to, e.g. add some logging or whatever).
On the other hand, you work with an instance of a Scheduler (if you want testable code, you'll use dependency-injection to get a instance of a scheduler and will never call Scheduler.get() except in your DI "factory"). In a test, you can then use a StubScheduler for instance.
Then there's Timer, which is similar to the others but the scheduled task can be cancelled. Note that Timer makes use of JSNI too, just like DeferredCommand; any kind of code that uses a Timer will need a GWTTestCase to be unit-tested.

Java static TimerTask shutdown

I have a static, periodic, java Timer/TimerTask that I would like to shutdown when the app does. I don't want the app hanging because some thread is still running (like what happens in debug mode in eclipse, some environments may kill the thing anyway). The reason I have it static is I plan to have some (very simple, probably just a counter) shared memory in all of the containing class's instances with the Timer so I feel class scope is appropriate.
My question is how best to do the shutdown of the Timer? Is this an appropriate time to use finalize? This timer seems benign enough that having a non-deterministic call to finalize may work? Would probably need to do some kind of instance counting to verify that there are no longer any instances of the class out there? Suggestions on ways to manage the shutdown of the static Timer are welcome.
pseudo code:
class foo {
private static Timer someTimer = null;
public foo() {
if(someTimer == null) {
someTimer = new Timer(new TimerTask(...));
}
}
//how should I shut this thing down?
protected void finalize() throws Throwable {
}
//or is better to have shutdown() called explicitly?
}
It all depends on what your app actually does, but in general there will be some kind of event to signal that the app is being shutdown. For example if it's a GUI app, then maybe this will be the "user clicked on the Quit button" event. Or it's a webapp based on the servlet API, it will be an event fired by a ServletContextListener.
You should add a listener for this event, which calls some kind of shutdown method on your foo object. Inside this shutdown method the foo should take care of cleaning up its resources, including stopping the timer.
As a last resort, you might want to investigate JVM shutdown hooks

Is my way of doing threads in Android correct?

I'm writing a live wallpaper, and I'm forking off two separate threads in my main wallpaper service. One updates, and the other draws. I was under the impression that once you call thread.start(), it took care of everything for you, but after some trial and error, it seems that if I want my update and draw threads to keep running, I have to manually keep calling their run() methods? In other words, instead of calling start() on both threads and forgetting, I have to manually set up a delayed handler event that calls thread.run() on both the update and draw threads every 16 milliseconds. Is this the correct way of having a long running thread?
Also, to kill threads, I'm just setting them to be daemons, then nulling them out. Is this method ok? Most examples I see use some sort of join() / interrupt() in a while loop...I don't understand that one...
No
No
For #1, I believe your threads are terminating. Once the run() method is left, the thread is considered terminated. If you want the thread to run "forever", you need to repeat your actions.
For #2, the thread will continue running even if you lose all references to it. I would suggest a signal or condition to the worker thread, followed by a join() in the main thread.
Like Yann said, if you keep having to restart your thread(s), it means you are probably not looping correctly.
Say your wallpaper just has a ball moving around the screen, this would be a sample run() method:
boolean isAnimating;
public void run() {
isAnimating = true;
while(isAnimating) {
moveBall();
isAnimating = isWallpaperVisible(); // or whatever conditions apply to not keep animating
}
}
This way your run method will keep running indefinitely.

Java multi-threading - what is the best way to monitor the activity of a number of threads?

I have a number of threads that are performing a long runing task. These threads themselves have child threads that do further subdivisions of work. What is the best way for me to track the following:
How many total threads my process has created
What the state of each thread currently is
What part of my process each thread has currently got to
I want to do it in as efficient a way as possible and once threads finish, I don't want any references to them hanging around becasuse I need to be freeing up memory as early as possible.
Any advice?
Don't think in terms of threads, which are OS objects and carry no application semantics, but in terms of tasks. A Thread cannot know it is 50% complete, a task can. Look at the facilities in java.util.concurrent for managing tasks in terms of executors and callable objects.
In most cases where you're using Java (i.e. non-embedded systems) you should not care how many threads your process has created any more (or any less) than how many objects it has created - you don't want to run out, but if you are explicitly managing OS resources in a high-level language you're probably working at the wrong level of abstraction.
For intermediate feedback, create a progress listener interface containing a method for informing the listener where the task has got to, pass it to the task on creation and call it during your task when the progress changes. Make sure any implementation of the interface is thread safe.
It seems that the information you are looking for is mostly app specific ("what part of my process each thread currently does?"). Even, "how many total threads my process has created" is app specific because you are not interested in all sort of threads that the JVM has created (GUI, GC, etc.).
Thus, the best course of action is to create your dedicated subclass of Thread. What the thread start/finish processing a job your class will register the necessary details with some central registry.
[EDIT]
Here's a typical implementation (can be refined further):
public class MyThread extends Thread
{
private Runnable runnable;
private String description;
private Registry reg;
public MyThread(Runnable runnable, String description, Registry reg) {
this.runnable = runnable;
this.description = description;
this.reg = reg;
}
public void run() {
int id = reg.jobStarting(description);
try {
runnable.run();
reg.jobEnded(id);
}
catch(Throwable t) {
reg.jobFailed(id, t);
}
}
}
Use JMX: http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html
Add the following parameters to your jvm (after javac ...):
-Dcom.sun.management.jmxremote.port=8086 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false
Then connect using jconsole. JConsole will be in the bin folder of your JDK. I am sure it comes with the JDK but i'm not sure if it's bundled with the JRE. In this case, when JConsole pop's up, enter localhost:8086 as the ip address. Change the port if needed.
In JConsole, click on the Thread tab. This will show you the number of running and started threads with a nice graph. You can also click on the thread to see the current stack trace. You even have a button to detect dead locks!
I would change the design approach altogether and reason with Work instead of Threads.
You chunk your big task into work that you submit to executors/worker (see also the thread pool pattern). Then you can register listener that get notified when a work is started/completed/aborted.
The JCA specification implement this pattern in the WorkManager, you can draw some inspiration from it:
void scheduleWork(Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener)
And the listener
void workAccepted(WorkEvent e);
void workCompleted(WorkEvent e);
void workRejected(WorkEvent e);
void workStarted(WorkEvent e);
Otherwise have a look at the java.util.concurrent there is also some interesting stuff in it.
Use Visual VM from sun/oracle, free tool. Pretty good tool, gives you lot of details about threads, memory used, cpu for the process running.

Categories