|

So you have a background task that takes too long to finish. You want to set a timeout value, after which
the task is automagically cancelled.
Of course there're lots of solutions for handling this. The very first one could think of is keeping track of
time in any background loop (if any) and deciding if it's time to timeout the task. Something like this:
public String doInBackground() throws Exception
{
long startTime = System.currentTimeMillis();
for( ... )
{
// Check if we've been running for more than 100 ms...
if ( System.currentTimeMillis() - startTime > 100L )
cancel();
... keep on doing things
}
...
That's a naive solution that fails if any of those operations in the loop is a blocking operation, since
then the "if" is not evaluated and the operation is not cancelled.
So what's a better solution that works on all cases? Well, the solution requires using ... SwingWorkers!!
Imagine you've got a SwingWorker with your stuff. Let's call this the "worker" SwingWorker.
Now we can build another SwingWorker, a wrapper one, let's call it "Timer". What this "Timer" SwingWorker does
is just executing the other SwingWorker and invoking "get(long,TimeUnit)" to wait for the result of the
"worker" SwingWorker. If the result is not available within that timeout the "Timer" SwingWorker will cancel the
"worker" SwingWorker. Let's see the code...
@Override
protected R doInBackground()
throws TimeoutException, InterruptedException, ExecutionException
{
worker.execute();
try
{
return worker.get( timeoutValue, timeUnit );
}
catch( TimeoutException timeoutException )
{
worker.cancel(true);
throw timeoutException;
}
}
That's easy, right? Well, the drawback is that we need two SwingWorkers. The benefits are that
timing is accurate and that the worker SwingWorker is cancelled even with blocking operations.
Obviously you can enhance that as you want. Instead of cancelling the "worker" you could just pop-up a
progress dialog, informing the user of the advances of the "worker" SwingWorker and presenting an
optional Cancel button, if you like. I'll post examples for this in the future.
Enjoy Swing meanwhile,
Antonio
|