0

When i enclose Thread.wait() in a while loop my IDE (NetBeans) tells me that this may cause perfomance issues, how can it and is there a way arround it?

Example:

    while (timing){
        Thread.wait(10);
        foo++;
        }
    //Started in a seperate thread before activating.

EDIT: Thanks for the help, I will try to use the 'ScheduledExecutorService' instead!

rob5300
  • 138
  • 7
  • Same question here: http://stackoverflow.com/questions/3956512/java-performance-issue-with-thread-sleep – NickL Jan 23 '14 at 10:15
  • Give more background, it is difficult to say if it would be better to sleep or to wait without more information... – assylias Jan 23 '14 at 10:17
  • Class `Thread` does not have a static method `wait`. I hope you have not declared a variable named `Thread`. Are we talking about the same `java.lang.Thread` or is your Thread another class? – René Link Jan 23 '14 at 10:18
  • In something like a game-loop, a delay of 10ms should be OK. The question linked by NickL contains more information on the cases where such a sleep CAN cause performance issues. – Marco13 Jan 23 '14 at 10:25

1 Answers1

0

You probably wanted to just make the thread sleep, and that is the name of the method you needed to call.

You called Object#wait(), which is a thread coordination method, and you used an explicit timeout on it (a rather short one). My guess is that NetBeans is warning you about that timeout because normally we use Object#wait without a timeout, and if we use the timeout, we don't wait in a loop.

Now, NetBeans will also warn you about using Thread.sleep() in a loop because normally, if you want to schedule a repeated task (that is what you are doing), you will use a ScheduledExecutorService. That service is able to serve a lot of different scheduled tasks around your application, all with a single thread. Writing Thread.sleep() explicitly in a loop needlessly hogs a whole thread (a heavyweight system resource) to do nothing but sleep most of the time.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436