Why is there a need to use purge() of java.util.TimerTask? - java

Timer.cancel(): Cancels the task.
Timer.purge(): Remove all cancelled tasks from this timer's task queue.
What would happen when I would not use purge() here? What would happen when the timer's task queue got filled?

Nothing will change as to the actual Timer behaviour unless you have an ungodly number of timers going on. The cancel method does stop the timer running, but the program will still keep a reference to the timer even after its been cancelled, and so the memory it used will still be in use. The purge method allows Java to mark the timer references for garbage collection, allowing the memory they are using to be used for something else.
Most programs will not need to use the purge method, its just there for programs that will use a lot of timers, either many in a short burst, or if a program is going to be running for many days at a time.

Related

Using less Timers

It doesn't really lag that much in my game but I know that I could reduce a lot of lag in my game by having less Timer's running. The game have multiple Timer's because it have one Timer that updates everything like the players location and all the obstacles then I have other Timer's that I use to remove the power ups that you could get.
For example I have one Timer that have it's initial delay set to 5000 and when it is runned one time (it will only run one time) it will remove a specific power up and the I have another Timer that have it's initial delay set to 20 000. How would I keep the different delay of each timer but still only using one or at least fever than I use now?
Is there anyway that I could use PriorityQueue or ScheduledThreadPoolExecutor to accomplish this? and if so how?
You would schedule tasks on the ScheduledThreadPoolExecutor, and then re-schedule them for a different delay if you want to run the same task again.
Another option is to use a DelayQueue to store the tasks you want to execute, and use a separate thread to take and execute runnables off of the queue. As with the ScheduledThreadPoolExecutor you'd have to put the runnables back on the queue with a new delay if you want them to run again.
The ScheduledThreadPoolExecutor lets you schedule tasks to continually run after a fixed delay, whereas the DelayQueue requires you to keep putting the task back on the queue after it's run.
Why would there be a timer that "updates everything"? Updating should always execute non-stop. (Unless you want to limit your game to constant FPS)
You really should consider abusing the "Game Loop":
While Game Is Running
Update()
Draw()
End While
If you don't want any lags in your game, you need to consider always updating player location, etc...
That said, when you update locations, etc... you need to make sure you make them relative to the time elapsed since last time Update() was executed.
If you're not constantly calling Update(), then you're going to have lags no matter what threading pattern you use.

Executing some code after a specific amount of time

I need to execute an action after a specific amount of time (for example 30 minutes after the app started up, if the app is still up).
What are my options and will it necessary means there's going to be one thread "lost" waiting for the 30 minutes to pass by?
Ideally, at program startup, I'd like to do something like the following (simplified on purpose) and then don't have to think about it anymore:
doIfStillUp( 30, new Runnable() {
....
});
So how should I go about implementing doIfStillUp(...)?
Should I use a TimerTask? The Executor framework?
Most importantly (it's for understanding purpose): does this mean there's going to be one thread lost idling for basically nothing during 30 minutes?
If there's going to be one thread "doing nothing", is this an issue? What if there are 10 000 threads (I'm being facetious here) "doing nothing"?
Note that I'm trying to understand the "big picture", not to solve a particular problem.
The Executor framework is a reasonable choice.
There's a schedule method that just takes a runnable and a delay time.
schedule(Runnable command,
long delay,
TimeUnit unit)
That's pretty straightforward. There won't necessarily be a thread blocked waiting on your task. You could use a ScheduledThreadPoolExecutor, as linked above that keeps X threads ready to run scheduled tasks.
You can imagine a data structure that holds the time at which a task should be run. A single thread can watch or set up these delays and can potentially watch thousands of them in a single thread. When the first time expires it'll run the task. Potentially using its own thread, potentially using 1 of X in the thread pool. When a new task is added or an existing task is finished it'll wait for the earliest time to arrive and then start the whole process again.
You should use a Timer. Its javadoc answers all your questions.
One thread is used for every timer, but the timer executes several tasks, sequentially. The timer tasks should be very short. If they aren't, consider using several timers.
Of course, the timer thread will be idle if it doesn't have any task to execute. An idle thread doesn't consume anything (or nearly anything), so I wouldn't worry about it. Anyway, you don't have many choices. 10000 threads doing nothing would of course be an issue, but that would mean that you instantiated one timer per task, which is wrong.
You can schedule task on java.util.Timer. For all timer tasks single timer thread will be created by java.util.Timer.
The builtin java timer is the straight away solution: http://download.oracle.com/javase/1,5.0/docs/api/java/util/Timer.html#schedule(java.util.TimerTask, long)

How do I make sure a Timer stays alive?

I have code that relies on a Timer staying alive and managing TimerTask. Usually TimersTasks will come and go and there will always be at least one TimerTask to keep the Timer alive, but every now and then all the TimerTasks will die and the Timer will die with it.
How would I keep Timer alive? Should I have one TimerTask in it at scheduled to fire at a far away date? That's what I'm leaning towards, but I want to hear what more experienced programer's ideas would be.
*It would also be nice if I could terminate all TimerTaks except for this one 'permanent' TimerTask.
Sorry if none of this makes much sense, or if I'm thinking of Timers and TimerTasks all wrong. I'm brand new to Java and all programming.
This sounds backwards. The Timer is the thing that manages the tasks. The TimerTask is the thing that is getting managed. You create a timer, you tell it to schedule the timertask, which can be singular or continuous (e.g. you can set the task to run every hour for as long as your JVM is running). It will run until it has no more tasks.
From the docs:
After the last live reference to a Timer object goes away and all
outstanding tasks have completed execution, the timer's task execution
thread terminates gracefully (and becomes subject to garbage
collection).

JAVA - Cancel the ThreadPoolExecutor running tasks

What I need is a method similar to shutdownNow, but, be able to submit new tasks after that. My ThreadPoolExecutor will be accepting a random number of tasks during my program execution.
You can grab the Future of each submission, store that Future in a collection, then when you want to cancel the tasks, invoke future.cancel() of all queued tasks.
With this solution the Exectuor is still running and any running tasks are cancelled or will not run if they are queued.
Why not create your own ExecutorService that exhibits this behaviour?
Is it not enough to just do getQueue() and clear it? If you really need to attempt to stop running tasks, you would need to subclass the ThreadPoolExecutor and essentially re-implement shutdownNow() but only copy the bit that sends an interrupt to each thread. Mind you this still isn't any guarantee that you will actually cause them to immediately cease and do no further calculation. You'll need a totally different approach if you need to do that.

What's the proper background process behaviour for a non-GUI Java app?

What's the proper way for a Java command line application to do background work without hogging resources? Should it use sleep() in the loop or is there a more elegant/efficient way?
Some heuristics:
Don't attempt to make scheduling decisions in your application. The operating system's scheduler is way better than yours will be. Let it do its job.
Don't poll if you don't have to. For instance, instead of sleeping n seconds, then waking up to check a non-blocked socket, block on the socket. This second strategy plays better with the operating system's scheduler.
Don't use an enormous heap if you don't have to, and try not to allocate enormous chunks of memory at one time. A thrashing application tends to have a negative effect on system performance.
Use buffered I/O. Always. If you think you need non-buffered I/O, be absolutely sure you're right. (You're probably wrong.)
Don't spawn a lot of threads. Threads are surprisingly expensive; beyond a certain point, more threads will reduce your application's performance profile. If you have lots of work to do concurrently, learn and use java.util.concurrent.
Of course, this is just a starter list...
I'd only use sleep() if there's no work to be done. For example, if you're doing something like polling a task queue periodically and there's nothing there, sleep for a while then check again, etc.
If you're just trying to make sure you don't hog the CPU but you're still doing real work, you could call Thread.yield() periodically. That will relinquish control of the CPU and let other threads run, but it won't put you to sleep. If other processes don't need the CPU you'll get control back and continue to do your work.
You can also set your thread to a low priority:
myThread.setPriority(Thread.MIN_PRIORITY);
As Ishmael said, don't do this in your main thread. Create a "worker thread" instead. That way your UI (GUI or CLI) will still be responsive.
There are several ways. I would use ExecutorService... for example:
ExecutorService service = Executors.newCachedThreadPool();
Callable<Result> task = new Callable<Result>() {
public Result call() throws Exception {
// code which will be run on background thread
}
};
Future<Result> future = service.submit(task);
// Next line wait until background task is complete
// without killing CPU. Of course, you can do something
// different here and check your 'future' later.
//
// Note also that future.get() may throw various exceptions too,
// you'll need to handle them properly
Result resultFromBackgroundThread = future.get();
This is Java 5 code, ExecutorService, Callable, Future and similar are in java.util.concurrent package.
One place to start is to make sure that only those resources are being used and no other objects (so that they become garbage collected).
Placing sleep() in a single threading application is only going to halt the current thread. If you're trying to accomplish data being processed in the background while information still needs to be presented to the user then it is best to put the background process in a seperate thread.

Categories

Resources