How to interrupt a thread with infinite loop and sleep in Java

1.2k views Asked by At

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;
    }

}
1

There are 1 answers

5
JiriS On

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.