Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid busy-waiting warning in a thread

Tags:

java

I have this piece of code:

public void foo(AtomicBoolean close){

    new Thread(() -> {

        try{

            System.out.println("foo started");

            while(!close.get()){

                System.out.print("working");
                //peace of code for execution.

                //wait 1 second before re-execute the same thing.
                //warning: Call to 'Thread.sleep()' in a loop, probably busy-waiting
                try{ Thread.sleep(1_000); /*1sec*/ }catch(Exception ignored){}

            }

        }catch(Exception e){
            e.printStackTrace();
        }

        System.out.println("foo stopped");
        

    }, "fooThread").start();

}

The code works, but I want to get rid of that warning and I don't see how I can rewrite this piece of code.

The close is just for knowing when the thread should stop.

like image 947
KunLun Avatar asked Mar 17 '26 04:03

KunLun


1 Answers

This is how I'd write it. You don't necessarily need the class, it just encapsulates the executor and task nicely.

In addition to scheduleWithFixedDelay, there's also scheduleAtFixedRate. The difference is explained here. I chose the one that's closest to your code.

class FooService
{ 
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    private volatile ScheduledFuture<?> task;
    
    public void start() {
        if (task != null) {
            throw new RuntimeException("Already started");
        }

        task = executor.scheduleWithFixedDelay(() -> {
            System.out.println("working");
            // piece of code for execution.
        }, 0, 1, TimeUnit.SECONDS);
    }
    
    public void stop() {
        task.cancel(true);
        executor.shutdown();
    }
}
like image 157
Michael Avatar answered Mar 19 '26 21:03

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!