This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interrupting a looping thread

 
Darryl Failla
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Edward Harned
Ranch Hand
Posts: 291
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[ 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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic