In our overview of Java queue types,
we said that perhaps the most significant type is the blocking queue.
A blocking queue has the following characteristics:
- methods to add an item to the queue, waiting for space to become available in the
queue if necessary;
- corresponding methods that take an item from the queue, waiting for an item to put in the queue
if it is empty;
- optional time limits and interruptibility on the latter
- efficient thread-safety: blocking queues are specifically designed to have
their put() method called from one thread and the take() method from another—
in particular, items posted to the queue will be published correctly to any other
thread taking the item from the queue again; significantly, the implementations generally achieve this
without locking the entire queue, making them highly concurrent components;
- integration with Java thread pools: a flavour of blocking queue can
be passed into the constructor of ThreadPoolExecutor
to customise the behaviour of the thread pool.
These features make BlockingQueues useful for cases such as the following:
- a server, where incoming connections are placed on a queue, and a pool of
threads picks them up as those threads become free;
- in a variety of parallel processes, where we want to
manage or limit resource usage at different stages of the process.
Example use of BlockingQueue
On this next page, we'll examine the facilities provided by BlockingQueue implementations.
We'll work through a BlockingQueue example,
using it to cosntruct a logger thread.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.