Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

interrupting a running task in a thread  RSS feed

 
tatae alvostru
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a thread processing task by task in the run method
while(running) {
Task = getTask();
porcess(task);
}
Sometimes (like process running too much) I might want to stop
a running task and make the thread skip to the next one.
What's the best solution ? (without creating a new 'clone')
Do application servers provide such a feature for an object (timeout or task interrupting) ?
 
Mo Ibrahim
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not a good idea to interrupt an executing thread. This will result in undefined state of the thread and lead to inconsistent results. If you think that you want to interrupt a thread, use a timer or other mechanisms to alter a variable whose value is checked by the thread and return normally out of the run method after cleaning up non-memory related resources.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's certainly nothing wrong with interrupting a running thread (as opposed to stopping it!) If your task wait()s or sleep()s reguarly, you don't need to do anything special except handling the <code>InterruptedException</code> they may throw. Otherwise, you could put code such as the following in the inner loop of your task:

And handle the exception at the appropriate level.
- Peter
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!