• Post Reply Bookmark Topic Watch Topic
  • New Topic

Stopping threads with interrupt()  RSS feed

 
Mike Nason
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a thread running and need to stop it, because of undeploying web app.
What I've done is the like the code below:

but that is not actually work! (test with profiler). When ear application is undeployed there were still some threads that are running, so I did the cancel flag like that

that is working good!
Why interrupt() is not working to stop the thread?
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
InterruptedException clears 'interrupted' flag,
and your loop is infinite because isInterrupted method always return false.
 
Istvan Kovacs
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For sake of safety, you'll want to make sure isCancelled is volatile, otherwise writing it from one thread may not be visible in another thread, especially in the server VM (it'll probably work with the client VM). You could also use synchronized blocks to read/write, or AtomicBoolean, or any other thread-safe object.
 
Olivier Legat
Ranch Hand
Posts: 176
Chrome Mac Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ireneusz Kordal wrote:InterruptedException clears 'interrupted' flag,
and your loop is infinite because isInterrupted method always return false.

Indeed,

If you wish to stop threads using interrupt() then something like this should do the trick:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!