How to avoid busy spinning in Java

前端 未结 4 2171
南旧
南旧 2021-02-09 16:02

I have a multi-threaded application where a thread sends a message to another thread. The waiting thread polls for the message and reacts (locks are handled). Like this:

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-09 16:38

    The correct way to avoid this is to use the wait/notify mechanism implemented by java.lang.Object, or one of the higher level concurrency mechanisms provided by the Java class libraries:

    • semaphores,
    • latches / cyclic barriers,
    • blocking queues; e.g. the classes that implemented the BlockingQueue interface.

    (Pick the mechanism that is the best match for what your specific use-case ...)


    Using Thread.sleep is not a good solution. While you reduce CPU load (compared with a polling loop), the flip-side is that you reduce responsiveness.


    I'm using a BlockingQueue now. But maybe I'm doing it incorrectly. I just added the actually code above. Do you see my problem?

    Yea. You are using the queue in a way that is designed to avoid blocking. That's the wrong approach. You should use take() (which will block until an entry becomes available) instead of poll(), and get rid of the code that tests the queue size.

    Your "killMeMailbox" stuff seems to be designed to allow you to stop waiting for mail. You should be able to implement that using Thread.interrupt. (An interrupt will unblock a take() call ...)

提交回复
热议问题