Synchronization and concurrency
Deadlock (and avoiding it)
Java 5: ConcurrentHashMap
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.
Article written by Neil Coffey (@BitterCoffey).
LetterMeister (word puzzle game for iPhone)
Currency Quoter (currency converter/predictor)
French Vocab Games for iPhone/iPad
Vocabularium: create Spanish vocab podcasts
Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey).
Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles,
or if you simply have a programming question that you would like to see answered on this site. Most topics
will be considered. But in particular, the site aims to provide tutorials and information on topics that
aren't well covered elsewhere, or on Java performance information that is poorly described or understood.
Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2013. All rights reserved.