i've been fighting with this over few hours now. Here's the code:
#Override
public void run()
{
try
{
wscript.setBid(0.30);
wscript.setServiceMode(WebScript.ServiceMode.ON);
for(;!Thread.currentThread().isInterrupted();)
{
Positioning(demandedPosition, maximumBid);
if(Thread.currentThread().isInterrupted())
break;
Thread.sleep(10000);
}
wscript.setServiceMode(ServiceMode.OFF);
Log("Algorithm has been canceled!");
}
catch (InterruptedException e)
{
wscript.setServiceMode(ServiceMode.OFF);
Log("Algorithm has been canceled!");
return;
}
The thing is, that i would like to interrupt it in legit way with this code:
private void StopService()
{
service.interrupt();
}
When I call this method when Thread.sleep() is running, it gets InterruptedException and everything works fine. However, as I call it when the PositioningAlgorithm is running nothing is happenning, the thread acts like it never got the interruption state.
Regards,
DualCore
EDIT: It is essential for me that the call Log("Algorithm has been canceled!"); will be executed after interruption.
SOLVED: I had overwritten Thread.interrupt() to edit class local variable which was checked whether the thread is ready to end:
service = new Thread(mechanism)
{
#Override
public void interrupt()
{
super.interrupt();
mechanism.ReadyToReturn = true;
}
};
And here's updated thread main algorithm:
#Override
public void run()
{
try
{
wscript.setBid(0.30);
wscript.setServiceMode(WebScript.ServiceMode.ON);
for(;!ReadyToReturn || !Thread.currentThread().isInterrupted();)
{
Positioning(demandedPosition, maximumBid);
if(ReadyToReturn || Thread.currentThread().isInterrupted())
break;
Thread.sleep(10000);
}
wscript.setServiceMode(ServiceMode.OFF);
Log("Algorithm has been canceled!");
}
catch (InterruptedException e)
{
wscript.setServiceMode(ServiceMode.OFF);
Log("Algorithm has been canceled!");
return;
}
}
The reason why this might be happening is that Positioning clears isInterrupted flag (see https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupted%28%29) and/or catches somewhere InterruptedException (or Exception/Throwable).
One possibility is to use another flag (e.g. using volatile variable/ AtomicBoolean/ThreadLocal) to indicate whether the thread should be interrupted.
Related
if I override my run function as ,
Thread t = new Thread(){
public void run(){
try {
if(Thread.currentThread().isInterrupted()) {
doSomePrcocess() // is the isInerrupted() flag seeting to true?
return; //Terminates the current Thread
}
//otherwise
runScript();
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
and then If I call, Thread.currentThread().interrupt() from any point in the code, should the thread halt there and start running doSomeProcess() at that point? if yes, then how the interrupted flag gets to set true? If no, how to do this?
If thread is in sleeping or waiting state calling the interrupt() method on the thread, breaks out the sleeping or waiting state
throwing InterruptedException
If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true.
Thread class has provision to deal with thread interruption as
public void interrupt()
public static boolean interrupted()
public boolean isInterrupted()
If you intend to go with the only once execution of doSomePrcocess then you have to go with which will check and clear the Thread interruption state for successive calls.
public static boolean interrupted()
Using below will only check the status and no modification.
public boolean isInterrupted()
I have got a running example with comments in your code below. Try running it a few times to see if it clarifies your concept.
Normally you would interrupt a thread from another thread and yes doSomeProcess will get invoked in the next cycle of the loop which could be 1 ms after the thread was interrupted or 1 hour after depending on the logic implemented in your methods.
public class InterruptTest {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread() {
public void run() {
while (true) {
try {
if (Thread.currentThread().isInterrupted()) {
doSomePrcocess(); // is the isInerrupted() flag seeting to true? - Yes
return; // Terminates the current Thread - yes
}
// otherwise
runScript();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void runScript() {
System.out.println("runScript interrupted status:" + this.isInterrupted());
sleepy(100);
}
private void doSomePrcocess() {
System.out.println("doSomePrcocess interrupted status:" + this.isInterrupted());
sleepy(500);
}
private void sleepy(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Thread.currentThread().interrupt(); // try commenting this out to see what happens.
}
}
};
t.start();
Thread.sleep(1000);
t.interrupt(); // generally you would call interrupt on another thread.
}
}
No, it doesn't work like that. The isInterrupted method checks if the flag is set, it does not declare a handler. There is no way to define a central handler that will automatically be called when a thread is interrupted. What you can do is to catch InterruptedException and call the handler, plus check the interrupt flag regularly to see if it is time to stop.
In this code
public class NoncancelableTask {
public Task getNextTask(BlockingQueue<Task> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrupted = true;
// fall through and retry
}
}
} finally {
if (interrupted)
Thread.currentThread().interrupt();
}
}
interface Task {
}
}
I understand that setting the interrupted status lets the caller of this method retain the status of interruption to do something with it according to the methods policy.
However Goetz also says that this method is used for "activities that do not support cancellation"
So my question is whats even the point of doing that if its never even going to go into the finally block and back up the call stack to its caller?
I am starting a new thread in my app's onCreate() method like so:
stepsLogger = new Runnable() {
while(!Thread.currentThread().isInterrupted()){
//my code
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
loggerThread = new Thread(stepsLogger);
loggerThread.start();
While it is not interrupted, it is supposed to do its thing every 10 seconds.
I am logging some text at the start of the Runnable to see how often the code gets run. The first time I run the app it's fine, but every time i restart, the text gets logged more frequently which means that more threads are running.
I have tried to stop them in the onDestroy() method:
#Override
protected void onDestroy() {
super.onDestroy();
loggerThread.interrupt();
loggerThread = null;
}
How do I make sure that the old thread gets stopped whenever the app is restarted?
Thread.interrupt() will wake up a sleeping thread with an InterruptedException, so you're most of the way there already. I'd change your loop in the following way:
while (true) {
// some code
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the thread's interrupted flag
break;
}
}
The bit about re-interrupting the thread is subtle. You can read more about it in this post from one of the primary JVM architects: https://www.ibm.com/developerworks/library/j-jtp05236/
In case this link ever dies, the gist of it is that there can be multiple "recipients" of thread interruption. Catching the exception implicitly clears the thread's interrupted flag, so it's useful to set it again.
You could use a volatile boolean variable to determine when to stop. Something like this:
class WorkerRunnable implements Runnable {
private volatile boolean shouldKeepRunning = true;
public void terminate() {
shouldKeepRunning = false;
}
#Override
public void run() {
while (shouldKeepRunning) {
// Do your stuff
}
}
}
To start it:
WorkerRunnable runnable = new WorkerRunnable();
new Thread(runnable).start();
To stop it:
runnable.terminate();
When I tried to figure out how to stop a thread in a program with multiple threads,
I was suggested to call a method which actually sets a flag to tell that thread stop doing real works,like this:
public class ThreadTobeTerminated implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean running = true;
public void terminate() {
running = false;
}
#Override
public void run() {
while (running) {
try {
LOGGER.debug("Doing some real work ,like Counting...");
for(int i=0;i<100;i++){}
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
running = false;
}
}
}
}
when I want to stop this tread ,I'll call threadInstance.terminate();.
Don't I need to literally stop this thread ?
Why I should leave this thread to do some useless work (method run called ,test the flag running==false then return)? I mean :this is a waste of time ,isn't it?
When the execution scope goes beyond the run() method, the thread stops, so the moment that the while loop is broken, the thread will stop.
This would also allow you to do some clean up if the situation requires it:
public void run() {
while (running) {
try {
LOGGER.debug("Doing some real work ,like Counting...");
for(int i=0;i<100;i++){}
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
running = false;
}
}
//Clean up
}
The above approach allows you some control over how is the thread stops and what happens after as opposed to potentially just kill it, which could cause all kinds of problems.
Could someone please tell me how to stop a thread if I have the following structure?
I want to stop the thread B after it expires thread C.
c = new c();
c.start();
b = new b();
b.start();
class c extends Thread {
#Override
public void run() {
// DRAW IMAGE
// b.stop(); - doenst work
}
}
class b extends Thread {
#Override
public void run() {
// PROGRESS BAR
}
}
There is no good way to stop a thread instantly.
There is Thread.stop(), but it is dangerous and deprecated. Don't use it unless you have thoroughly analyzed your code and determined that the risks are acceptable.
There is Thread.interrupt(), but there is no guarantee that the thread will stop quickly, or even stop at all.
For Example:
while (!Thread.interrupted()) {
try {
//do stuff
} catch (InterruptedException e) {
// end up
}
}
There is the approach of writing the thread to periodically check a flag, but if the flag is not checked frequently (by accident or by design), then the thread won't stop quickly.
Please Refer to this for more details
Don't use .stop() use interrupt() instead
You need to check periodically in your b thread if it gets interrupted, if interrupted , you can take proper actions -
if(b.isInterrupted()){
//end your work
}
---> http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
Don't use Thread.stop() method, It's already deprecated, in this case you can handle the stopping of the b thread in your code.
For example:
class b extends Thread {
private volatile boolean stopped = false;
public void stop () {
stopped = true;
}
#Override
public void run() {
// PROGRESS BAR
while ( ! stopped ) {
// paint the progress bar
}
}
}
You might want to take a look at this. You can use a flag or just use Thread.currentThread().interrupt(), you can check if a thread is interrupted by calling Thread.isInterrupted() on it.
The solution to this is explained quite well here. Any thread that might need a status flag for shutdown could have the following structure:
volatile boolean shutdownRequested;
...
public void shutdown() { shutdownRequested = true; }
public void doWork() {
while (!shutdownRequested) {
// do stuff
}
}
Thus, in your case, your class B would look similar to the above. And then, in class C, you can call the shutdown() method of class B.
create a lockable object in your calling code
Boolean canRun = true;
c = new c();
when b has finished set canRun to false
periodically check value of canRun in c
Well, try this :
while(true) {
if (!c.isAlive() && b.isAlive()){
b.interrupt();
}
}
Try something like
private void startActionPerformed(java.awt.event.ActionEvent evt) {
p=new Progress();
myThread=new Thread(p);
p.setLocationRelativeTo(null);
p.setVisible(true);
myThread.start();
}
private void stopActionPerformed(java.awt.event.ActionEvent evt) {
if(myThread!=null){
p.Terminate();
try {
myThread.join();
} catch (InterruptedException ex) {
Logger.getLogger(ClassA.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
////////////////////////////////////////////////////////////////
How it Works and Stopped!
int i;
volatile boolean running=true;
public void run(){
while(running){
for(i=0;i<=100;i++){
pro.setValue(i);
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(Progress.class.getName()).log(Level.SEVERE, null, ex);
return;
}
if(i==100){
Terminate();
break;
}
}
}
}
public void Terminate(){
running=false;
}
/////////////////////////////////////////////////////////////////////
Use a Boolean flag.
For Thread safety, use AtomicBoolean.
AtomicBoolean running = new AtomicBoolean(Boolean.TRUE);
In your run() method check this flag in a while condition:
public void run(){
while(running){
...
}
}
When you want to stop this Thread, change the running to false