1

I want to log progress of some method in a specific time interval (avoiding logs overflow). I made this:

while (!x.isFinished()) {
     LOG.info("some progress: {}", x.getStatus());
     Thread.sleep(5000); 
}

As far as sonar tells it's bad practice to use Thread.sleep(n) and flag it as critical, I'm looking for better, proper way to make it. Is there something what I can improve?

The message is:

Using Thread.sleep in a test is just generally a bad idea. It creates brittle tests that can fail unpredictably depending on environment ("Passes on my machine!") or load. Don't rely on timing

Edit: This is not a duplicate, it's not a test. I want to log the time during working cycle each x interval.

Edit 2 (clarification according to @Wolf S answer): Thanks for reply. It is used in multiple place, I want to know each time which place is it. It's examplary code. What is more, it gives me some knowledge how much time it needs to finish during it's life and help diagnostics.

I just want to know if there is maybe some strict way to do it or just ignore sonar.

Vaix
  • 49
  • 1
  • 9

2 Answers2

0

Make your method (or object 'x') log its progress by itself.

Or make it call some callback method regularly to report progress which you can use to inject logging output (or updating a progress bar or whatever you want).

Wolf S
  • 236
  • 1
  • 3
0

If this is not a test then there is no problem in your code. (There might be depending on the rest of the code but generally speaking using Thread.sleep is not automatically a bad idea)

Oleg
  • 6,124
  • 2
  • 23
  • 40