5.9. Using a Blocking Buffer


Your system needs to wait for input and act on an object the moment it is added to a Buffer. To achieve this, you need your application to block until input is received.


Use BlockingBuffer to decorate an instance of Buffer. When a process calls get( ) or remove( ) on a buffer decorated with BlockingBuffer, the decorated buffer does not return a value until it has an object to return. The following example creates a BlockingBuffer and a listener that calls remove( ). A BlockingBuffer can only be demonstrated by an example that deals with multiple threads, and the following code uses a Runnable implementation, BufferListener, which is defined in Example 5-8:

import java.util.*;
import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.buffers.BlockingBuffer;
import org.apache.commons.collections.buffers.BoundedFifoBuffer;

// Create a Blocking Buffer
Buffer buffer = BlockingBuffer.decorate( new BoundedFifoBuffer( ) );

// Create Thread to continously remove( ) from the previous Buffer
               BufferListener listener = new BufferListener(buffer);
Thread listenerThread = new Thread( listener );
listenerThread.start( );

buffer.add( "Hello World!" );
buffer.add( "Goodbye, Y'all." );

The previous example creates an instance of BufferListener—a Runnable object that calls remove( ) on a BoundedFifoBuffer decorated with BlockingBuffer. The listenerThread will block on a call to buffer.remove( ) within the run( ) method of

Get Jakarta Commons Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.