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 looping thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Interrupting a looping thread" Watch "Interrupting a looping thread" New topic
Author

Interrupting a looping thread

Darryl Failla
Ranch Hand

Joined: Oct 16, 2001
Posts: 129
There doesn't appear to be any elegant way of interrupting a thread that is stuck in a loop using Java 1.4. Is that true?

It also appears that the thread interrupt method of 1.5 may be more powerful and allow this action.


Darryl Failla
Sun Certified Java 2 Programmer
Edward Harned
Ranch Hand

Joined: Sep 19, 2005
Posts: 291

Not quite.

No thread can be interrupted unless it wants to be.

You can have your base thread constantly check for isInterrupted(). That doesn't tell you anything about who did it or why you've been interrupted.

You can have a variable in the base thread that another thread sets (in a sync method or statement) and have your base thread constantly check that variable. That's a much preferred method.

In 1.5+, the variable can be volatile and if only one thread modifies it, then you don't need the sync.


Ed's latest article: A Java Parallel Calamity http://coopsoft.com/ar/Calamity2Article.html
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
[ January 07, 2007: Message edited by: Nicholas Jordan ]
[Since posting this, I have read that one cannot do an interrupt on System.in - it will not work]

Originally posted by Darryl Failla:
There doesn't appear to be any elegant way of interrupting a thread that is stuck in a loop using Java 1.4. Is that true?




Stuck in a loop should make no difference.

It also appears that the thread interrupt method of 1.5 may be more powerful and allow this action.

I would not think the interrupt() of 1.5 to be greatly different from 1.4 - at least conceptually from a coders point of view. There may be efficiency concerns at runtime that are producively addressed by this question, but only if you are applying Java to a time-critical performance arena.

What would be the compile options to show the the thread interrupt method of 1.5 may be more powerful ?
[ April 22, 2007: Message edited by: Nicholas Jordan ]

"The differential equations that describe dynamic interactions of power generators are similar to that of the gravitational interplay among celestial bodies, which is chaotic in nature."
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Interrupting a looping thread