Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Implementing Cancel Operation

 
Bhagya Tangutur
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the ncie way to implement Cancel Operation.
say i issued a command based on user operation,but suddenly user wants to stop the operation.I don't like to execute single statement
after user sends operation cancel request.besides i don't like to check some condition before executing each statmet.
thanks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need to check a condition before EVERY statement, but the best way to implement a "cancel" functionality is to have your long-running operation check some condition periodically. Response within a half-second or so is perceived by the user as instantaneous -- and millions of statements can execute in that amount of time! Of course, most long-running operations are loops, and you'll typically check the condition each time around the loop.
Often one thread is running some operation, while another is waiting for it to complete using join() or wait(). In this case, you can interrupt the waiting thread, and it will return immediately; then you can set the condition so the task thread will stop eventually. This kind of "two-phase" cancel works nicely.
The alternative to polling a condition is to use Thread.stop() -- and really, you don't want to do that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic