Restricting thread count and Java concurrency

后端 未结 4 476
北海茫月
北海茫月 2021-01-14 06:51

I couldn\'t find an example of this specific case using the latest JAVA concurrent routines.

I plan to use threads to process items from an open queue w

4条回答
  •  隐瞒了意图╮
    2021-01-14 07:27

    If you don't actually have access to the creation of the threads, and you only manage the queue access, a solution could simply be to use a Semaphore object (see the docs page).

    The idea is for a global semaphore, accessed in the same way the queue is accessed, to be initialized to the number max_threads (say, 10).

    Before accessing the queue for item processing, a thread would first acquire a permit from the semaphore, which would block if a max_threads number of threads had already started processing items from the queue.

    After an item is processed by some thread, that thread should finally release the permit, thus allowing more threads to process other items.

    Note that the acquiring/releasing of a permit should be done using a try-finally block, so that even if some exception is thrown from the item processing, the semaphore remains in a consistent state. The code should look like this:

    semaphore.acquire().
    try {
        // retrieve item from queue and process it
    }
    finally {
        semaphore.release();
    }
    

提交回复
热议问题