jedi_mind_ java jedi_mind_ java - 3 months ago 8
Java Question

Java - Runnable confusion

As I have already mentioned I am pretty new to programming world.
I am currently facing a problem with runable. When I am checking the status of boolean shutdown the code is running all the time, instead of expected every 30 seconds.
My code so far:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestClass {
static boolean shutdown;


public static void main(String[] args) {


notify(30);
}

private static void notify(int num) {

Runnable runner = new Runnable() {
public void run() {
while(!shutdown){
System.out.println("running");
}
}
};

ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleAtFixedRate(runner, 0, num, TimeUnit.SECONDS);
}

}


Edit: I need somehow to stop the method from running, that's why I have used boolean shutdown.

Answer

The while loop is causing the thread to tight spin forever. I bet your computer is showing 100% core usage when this runs.

ScheduledExecutorService.scheduleAtFixedRate returns an ScheduledFuture<?> object. What you need to do is call cancel() on it to stop the task from executing.

You need to remove the while loop and cancel the ScheduledFuture<?>.

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

I typed this into notepad - it probably won't compile but you should get the idea.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestClass {
static ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
static boolean shutdown = false;


public static void main(String[] args) throws Exception {
     new ShutdownChecker(30);
     Thread.sleep(90_000);
     shutdown = true;
}

private static class ShutdownChecker implements Runnable
{
    private final ScheduledFuture<?> future;

    public ShutdownChecker(int time)
    {
        future = TestClass.exec.scheduleAtFixedRate(this, 0, num, TimeUnit.SECONDS);
    }

    public void run()
    {
        if(TestClass.shutdown)
        {
            future.cancel();
            System.out.println("not running");
            return;
        }

        System.out.println("running");
    }
}

}
Comments