Sunday 27 September 2015

Producer Consumer Implementation - Blocking Queue

The Producer-Consumer design deals with the solution when different threads are involved in accessing the same shared resource to take or put elements from/to it.

- A consumer, thread class that removes one element from a resource.
- A producer, thread class that adds elements into a resource.
- A shared resource, called also monitor, will be a queue where the elements will be put and taken.

Originally this problem can be solved applying the methods wait() and notify(), and synchronizing the monitor.

The problem can be more simple using one of the collections of the concurrency package as blocking Queue (since 1.5).

BlockingQueue:
public interface BlockingQueue<E> extends Queue<E>

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
Definition from: 
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html

This collection is part of java.util.concurrent package and its main feature is that provides internal locks and concurrency mechanism to be accessed atomically (thread-safe). The methods that can be used to implement the consumer-producer are: put / take.

Example:
Output:
Consumer takes0
Producer puts 0
Producer puts 1
Consumer takes1
Producer puts 2
Consumer takes2
Producer puts 3
Consumer takes3
Producer puts 4
Consumer takes4
Producer puts 5
Consumer takes5
Producer puts 6
Consumer takes6
Consumer takes7
Producer puts 7
Consumer takes8
Producer puts 8
Consumer takes9
Producer puts 9

No comments:

Post a Comment