3

I am going to have to implement some functionality to my application soon that timesout a swing worker based on a user dictated length.

I was wondering if i could extend the swingworker class and add my own time out countdown inside, for example i could override the dowork method, call startCountdown() then call super.dowork and then keep checking if the timeout has been exceeded?

I was wondering if there were a better solution that this approach? Thanks

mKorbel
  • 109,107
  • 18
  • 130
  • 305
Biscuit128
  • 5,026
  • 21
  • 84
  • 142

2 Answers2

5

The javadocs for SwingWorker suggest this:

Because SwingWorker implements Runnable, a SwingWorker can be submitted to an Executor for execution.

This would be an easy solution for the timeout functionality you desire.

Submit your SwingWorker to ExecutorService#submit. On the resulting Future<?>, you may implement e.g. a timout of 10 seconds by

Future<?> f = service.submit(mySwingWorker);
try {
    f.get(10, TimeUnit.SECONDS);
} catch (ExecutionException ex) {
    /* SwingWorker threw an Exception */
} catch (TimeoutException ex) {
    /* SwingWorker timed out */
} catch (InterruptedException ex) {
    /* Thread got interrupted */
} catch (CancellationException ex) {
    /* would only be thrown in case you
       call #cancel on your future */
}
emboss
  • 37,929
  • 7
  • 96
  • 104
2

Use a Swing Timer ?

If it goes off, time is exceeded. Cancel it before that to stop it.

Brian Roach
  • 74,513
  • 12
  • 132
  • 160
  • just in case anyone finds this, i used the following solution to solve https://blogs.oracle.com/swinger/entry/swingworker_timing_out_slow_ones – Biscuit128 Feb 13 '12 at 19:37
  • Duplicate of http://stackoverflow.com/questions/7042186/swingworker-timeout which has a better answer – seinecle May 26 '14 at 18:36