File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes interrupting a running task in a thread Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "interrupting a running task in a thread" Watch "interrupting a running task in a thread" New topic
Author

interrupting a running task in a thread

tatae alvostru
Greenhorn

Joined: Jun 04, 2001
Posts: 17
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

Joined: Jul 10, 2001
Posts: 28
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

Joined: Apr 20, 2000
Posts: 3252
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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: interrupting a running task in a thread
 
Similar Threads
kicking off independent task threads in parallel
Updating a Thread variable.
Exception in timer : IllegalStateException
stopping a runnable in ThreadPoolExecutor
How to add a timeout value when using Java’s Runtime.exec()?