Monday, 22 March 2010

Java.util.Concurrent, Part 3 - Queues

In multi-threaded programming, its common to have both producers that create or
retrieve from something external, and also consumers that process what ever retrieved. Since there no knowing in general how quickly either process happen. In between we need a Queue of objects waiting to be processed. Java.util.Concurrent adds blocking queue. Queues are extensions to the collections API which means you can use the generics mechanism to state what type of object you put into them. Here are the basic methods common to any blocking queue. Where a non block queue was has methods that throw exception if the queue is too empty or too full, a block queue has methods that wait until the situation is resolved. Blocking queue operation may be considered atomic from the point of view of threads.

voidput(O)Adds a element to the queue, or waits for space.
booleanoffer(O)Adds a element to the queue, if there is space or returns false.
booleanoffer(O, long timeout, TimeUnit unit)Adds a element to the queue, or wait so long for space then returns false.
Objecttake()Take an element from the head of the queue, or waits for one to be there
booleanpoll(long timeout, TimeUnit unit)Adds a element to the queue, or waits the given time for space.

You can also measure fullness of the queue with remainCapacity() or copy all the element to another collection with drainTo().

Standard Queue backed by LinkedLists or Arrays are both available as our.

Backed by a linked list

ArrayBlockingQueueBacked by any Array
DelayQueueeach element .getDelay(), the take method take the element whose .getDelay() method has fallen further below zero, or wait until then
PriorityBlockingQueueThe priority, the first element to be returned is order by a Comparator (or Natural ordering, alphabetical for String etc)
SychronousQueueStores nothing, waits until both a take and a put thread are blocking at the same time.

No comments:

Post a Comment