title: Bounded Stream like implementation in java
body: <p><strong>Goal</strong>:</p>
  
  <ol>
  <li>I am looking for a bounded byte stream like implementation in java to have "write" and "read" functionality. </li>
  <li>The write should be non-blocking and should drop if the capacity has been reached. </li>
  <li>Ideally, the max size of the stream should be given in the beginning so that dynamic memory allocation overhead is not present.</li>
  </ol>
  
  <p><strong>What I have tried</strong>:</p>
  
  <p>I have shared data structure using the following buffer class, shared between the producer and consumer:</p>
  
  <pre><code>public class Buffer&lt;T&gt; {
  
      private ArrayBlockingQueue&lt;T&gt; buffer;
  
      public Buffer(int maxSize) {
          buffer = new ArrayBlockingQueue&lt;T&gt;(maxSize);
      }
  
      public boolean offer(T o) {
          return buffer.offer(o);
      }
  
      public T take(){
          try {
              return buffer.take();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          return null;
      }
  
      public static void main(String[] args){
          Buffer&lt;String&gt; buffer = new Buffer&lt;String&gt;(10);
          buffer.offer("hello");
          System.out.println(buffer.take());
      }
  
  }
  </code></pre>
  
  <p>A Producer in Thread 1 which reads from a socket and sends data as follows:</p>
  
  <pre><code>private InputStream in;
  
  while ( (bytesRead = in.read(request)) != -1) {
     this.register.buffer.offer(new ByteObject(request,bytesRead)
   }
  </code></pre>
  
  <p>A Consumer in Thread 2 which reads from the buffer and writes to a socket:</p>
  
  <pre><code>private OutputStream out;
  
  while(true){
     ByteObject poll = register.buffer.take();
     bytesRead = poll.len;
  
     if(bytesRead&gt;0){
         out.write(poll.arr,0,bytesRead);
         out.flush();
      }else
         break;
  }
  </code></pre>
  
  <p><strong>Problem with current implementation:</strong></p>
  
  <p>Since it is not a stream implementation, I am unable to detect EOF in the consumer. Can anyone give an example for Bounded Stream operations in java which give a non-blocking write option (like offer() functionality)</p>
  
  <p>Alternatively, how would I get EOF in the current code?</p>