O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.9. Using a Blocking Buffer

Problem

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.

Solution

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required