NetBeans / Java / New hint: Thread.sleep called in loop

后端 未结 4 1387
-上瘾入骨i
-上瘾入骨i 2020-12-08 09:10

In NetBeans, there\'s a new hint that says: Thread.sleep called in loop.

Question 1: How/when can it be a problem to sleep in a loo

4条回答
  •  北海茫月
    2020-12-08 10:05

    Calling sleep in a loop typically leads to poor performance. For example:

    while (true) {
        if (stream.available() > 0) {
           // read input
        }
        sleep(MILLISECONDS);
    }
    

    If MILLISECONDS is too large, then this code will take a long time to realize that input is available.

    If MILLISECONDS is too small, then this code will waste a lot of system resources check for input that hasn't arrived yet.

    Other uses of sleep in a loop are typically questionable as well. There's usually a better way.

    If it's a problem, what should I do instead?

    Post the code and maybe we can give you a sensible answer.

    EDIT

    IMO, a better way to solve the problem is to use a ThreadPoolExecutor.

    Something like this:

    public void listen() {
        BlockingQueue queue = new SynchronousQueue();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                1, Session.getMaxSessionCount(), 100, TimeUnit.SECONDS, queue);
        while (true) {
            try {
                queue.submit(new Session(database, serverSocket.accept()));
            } catch (IOException ex) { 
                ex.printStackTrace();
            }
        }
    }
    

    This configures the executor to match the way your code currently works. There are a number of other ways you could do it; see the javadoc link above.

提交回复
热议问题