Interrupting Threads without Exception

I

Icarus

The situation: have a program that consists of some 50+ classes. One
of the methods has to be interrupted after a set period of time. Hence
why I am using a Thread for this. The problems are:
- When the interrupt occurs, the program has to reverse some changes.
Having an InterruptedException thrown anywhere in the code is bad, as
I can't find out on which line exactly the exception happened and
which of the changes have already been made.
- The program calls multiple methods AND has to be as fast as
possible, so doing a manual check to Thread.currentThread
().isInterrupted() in every method is bad.


Below is some code replicating the problem. The goal is that the check-
attribute is set to the value "true" without having to change every

On a side note: the problem could easily be solved by having the
program check the time, i. e. passing the duration and starting time
and replacing
if(Thread.currentThread().isInterrupted()){
with
if(System.currentTimeMillis() - startingtime > duration){
.. However, this will be calculated a few thousand times. Is this
really more resources.heavy than creating a Thread for it?


package threads;


public class ThreadsJoin {

public ThreadsJoin(){

Ausfuehr ausfuehr = new Ausfuehr();
Thread thread = new Thread(ausfuehr);
thread.start();

try {
thread.join(1000);
System.out.println("Executed after join() without
InterruptedException");
} catch (InterruptedException e) {}

thread.interrupt();

System.out.println("Index: " + ausfuehr.index);
System.out.println("Check: " + ausfuehr.check);
}

/**
* This method spends some time manipulating values. It is to
be checked whether the interrupt
* occurs during this manipulation.
*/
public static void manipulate(){
int m=0;
for(int n=0; n<10000000; n++){
m++;
}
}

public static void main(String[] args) {
new ThreadsJoin();
}


class Ausfuehr implements Runnable{

long index;
boolean check;
Thread father;
boolean istUnterbrochen;

Ausfuehr(){
this.index = 0;
}

@Override
public void run() {
istUnterbrochen = false;
this.check = false;

this.runIndef();

this.check = true;
}

void runIndef(){

while(true){
if(Thread.currentThread().isInterrupted()){
return;
}

ThreadsJoin.manipulate();
index++;
}
}
}
}
 
L

Lew

The situation:  have a program that consists of some 50+ classes. One
of the methods has to be interrupted after a set period of time. Hence
why I am using a Thread for this. The problems are:
- When the interrupt occurs, the program has to reverse some changes.
Having an InterruptedException thrown anywhere in the code is bad, as
I can't find out on which line exactly the exception happened and
which of the changes have already been made.
- The program calls multiple methods AND has to be as fast as
possible, so doing a manual check to Thread.currentThread
().isInterrupted() in every method is bad.

Not really. Put it in a control loop within the thread.
Below is some code replicating the problem. The goal is that the check-
attribute is set to the value "true" without having to change every

On a side note: the problem could easily be solved by having the
program check the time, i. e. passing the duration and starting time
and replacing
if(Thread.currentThread().isInterrupted()){
with
if(System.currentTimeMillis() - startingtime > duration){
. However, this will be calculated a few thousand times. Is this
really more resources.heavy than creating a Thread for it?

Using a thread and a timer seems like the better choice to me.
package threads;

public class ThreadsJoin {

     public ThreadsJoin(){

          Ausfuehr ausfuehr = new Ausfuehr();
          Thread thread = new Thread(ausfuehr);
          thread.start();

Normally you'd want to avoid starting a thread from the constructor.
Since the thread instance refers to the invoker, were it not via a
static call, there would be a risk of damage due to the escape of the
incomplete 'this' to the thread.
          try {
               thread.join(1000);
               System.out.println("Executed after join() without
InterruptedException");
          } catch (InterruptedException e) {}

          thread.interrupt();

               System.out.println("Index: " + ausfuehr.index);
               System.out.println("Check: " + ausfuehr.check);
          }

          /**
          * This method spends some time manipulating values. It is to
be checked whether the interrupt
          * occurs during this manipulation.
          */
          public static void manipulate(){
          int m=0;
          for(int n=0; n<10000000; n++){
               m++;
               }
          }

          public static void main(String[] args) {
               new ThreadsJoin();
          }

     class Ausfuehr implements Runnable{

          long index;
          boolean check;
          Thread father;
          boolean istUnterbrochen;

          Ausfuehr(){
               this.index = 0;
          }

          @Override
          public void run() {
               istUnterbrochen = false;
               this.check = false;

               this.runIndef();

               this.check = true;

Have the interrupt handler set a flag to stop the thread, and check
the flag each time through your "infinite" loop instead of running
'while(true)'.
          }

          void runIndef(){

               while(true){

'while ( ! interrupted )' would be better.
                    if(Thread.currentThread().isInterrupted()){
                         return;
                    }

                    ThreadsJoin.manipulate();
                    index++;
               }
          }
     }

}

Read Brian Goetz's /Java Concurrency in Practice/, Addison-Wesley,
2006.
 
D

Daniel Pitts

Icarus said:
The situation: have a program that consists of some 50+ classes. One
of the methods has to be interrupted after a set period of time. Hence
why I am using a Thread for this. The problems are:
- When the interrupt occurs, the program has to reverse some changes.
Having an InterruptedException thrown anywhere in the code is bad, as
I can't find out on which line exactly the exception happened and
which of the changes have already been made.
InterruptedException can only be thrown at certain times.
- The program calls multiple methods AND has to be as fast as
possible, so doing a manual check to Thread.currentThread
().isInterrupted() in every method is bad.
Perhaps you can restructure this to be a state machine. That way, you
can have a "while (!shouldStop()) processNextState();" loop that handles
this all for you. With the added benefit that each "state" can have a
"rollback strategy" associated with it, if you need to undo certain
things on abort.
Below is some code replicating the problem. The goal is that the check-
attribute is set to the value "true" without having to change every

On a side note: the problem could easily be solved by having the
program check the time, i. e. passing the duration and starting time
and replacing
if(Thread.currentThread().isInterrupted()){
with
if(System.currentTimeMillis() - startingtime > duration){
.. However, this will be calculated a few thousand times. Is this
really more resources.heavy than creating a Thread for it?
If all you need to do is time-box a particular process, then perhaps you
should consider a different pattern altogether.

A dispatch loop seems like the best way to go, but without more details,
I can't really help.
 
K

Karl Uppiano

Icarus said:
The situation: have a program that consists of some 50+ classes. One
of the methods has to be interrupted after a set period of time. Hence
why I am using a Thread for this. The problems are:
- When the interrupt occurs, the program has to reverse some changes.
Having an InterruptedException thrown anywhere in the code is bad, as
I can't find out on which line exactly the exception happened and
which of the changes have already been made.
- The program calls multiple methods AND has to be as fast as
possible, so doing a manual check to Thread.currentThread
().isInterrupted() in every method is bad.

I'm not sure interrupting the thread is necessarily the right choice here.
If the thread is actively running, it could simply check a flag to see if it
is time to change course. If the thread blocks for any significant time (in
terms of your application), then interrupting it may be a good way to go.
The thread jumps to the interrupt handler. Generally, in a case like this,
the thread sets a state variable indicating what it is doing before it
blocks (or does anything else significant), and the handler checks the
variable to see what the context was when it was interrupted. After running
the handler, the thread may resume its normal operation. Keep in mind that
threads are sometimes also interrupted when it's time to shut down, so the
interrupt handler should check for that too.
 
I

Icarus

If all you need to do is time-box a particular process, then perhaps you
should consider a different pattern altogether.

A dispatch loop seems like the best way to go, but without more details,
I can't really help.

The program is a platform for the game Blokus with a module that
manages automatic players. Each player is assigned a period of time
that s/he is allowed to think about the move. The automatic player
continues searching for the best move until time runs out. I have the
search algorithm run in a separate thread and have the Facade of that
module wait for the specified time (a bit less actually).

The Facade uses the following code:

Thread searchThread= new Thread(searchAlgorithm);
searchThread.start();

try {
searchThread.join(suchdauer);
} catch (InterruptedException e) {}
if(suchThread.isAlive()){
searchThread.interrupt();
}

The search algorithm is split into three parts: the representation of
the board, the search algorithm itself and an evaluation function for
moves in maximum depth. It uses standard alphabeta search, i. e.
something like this:

search(depth, alpha, beta, gamma, delta) {

if(depth <= 0)
return evaluation.evaluate();

moves = representation.createMoves();
for(int n=0; n<moves.size(); n++){
rep.doMove()
result = search(depth-1, beta, alpha);
rep.undoMove();
if(result >= beta)
return beta;
if(result > alpha)
alpha = result;

if(Thread.currentThread().isInterrupted()){
return beta;
}
return alpha;

The three parts are interchangeable and I expect to have dozens of
evaluation functions. The problem is that I'd have to add
if(Thread.currentThread().isInterrupted())
to every function to prevent
searchThread.interrupt();
from interrupting the method midway. This part of the program and all
its methods will be called several thousand times.

Even if the check isn’t that costly, it looks very bad to just add the
check to every method and its sub-methods.
 
I

Icarus

Forget the gamma and delta in the above example. The algorithm is a
simplification from its four-player variant that uses four variables,
but otherwise works in a similar fashion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top