Is there a alternative to Thread.sleep in java

Here is my code

while (true) {
    try {
        Thread.sleep(5 * 60 * 1000);
        processData();// data processing job
    } catch (InterruptedException e) {
        SystemMessageBillPay.getInstance().writeMessage("ERROR: CEB.run() - " + e.getMessage());
    } catch (NumberFormatException e) {
        SystemMessageBillPay.getInstance().writeMessage("ERROR: CEB.run() - " + e.getMessage());
    }
}

to this

“Thread.sleep(5 * 60 * 1000);”

code inspector give warning

“Invoking Thread.sleep in loop can cause performance problems”

What should be the code to prevent this warning

Answer

Is there a alternative to Thread.sleep

Yes, there are ways. But,

It looks like you want to schedule some job. You can either use TimerTask or ScheduledExecutorService instead of this. So later part of your question is about the

“Invoking Thread.sleep in loop can cause performance problems”

and this will solve with scheduling the task.

Scheduling the Task.

public class Test extends TimerTask{

public static void main(String[] args) {
  Test task = new Test();
  Timer timer = new Timer();
  Calendar today = Calendar.getInstance();
  today.set(Calendar.HOUR_OF_DAY, 13);
  today.set(Calendar.MINUTE, 47);
  today.set(Calendar.SECOND, 0);
  timer.schedule(task, today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
}

 @Override
public void run() {
 System.out.println("Running Scheduled Task...!!!");
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *