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 BufferBufferListener 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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access