Beispiel #1
0
  /** Creates a pipe pair. The first object is a ReadStream, the second is a WriteStream. */
  public static Object[] create() {
    PipeStream a = new PipeStream();
    PipeStream b = new PipeStream();

    a.sibling = b;
    b.sibling = a;

    return new Object[] {new ReadStream(a, null), new WriteStream(b)};
  }
Beispiel #2
0
  public void close() throws IOException {
    if (readBuffer == null) return;

    synchronized (this) {
      readBuffer = null;
      readLength = 0;
      readOffset = 0;

      notifyAll();
    }

    synchronized (sibling) {
      sibling.notifyAll();
    }
  }
Beispiel #3
0
  /**
   * Implementation of the pipe write.
   *
   * @param buf byte buffer containing the bytes
   * @param offset offset where to start writing
   * @param length number of bytes to write
   * @param isEnd true when the write is flushing a close.
   */
  public void write(byte[] buf, int offset, int length, boolean isEnd) throws IOException {
    while (length > 0) {
      synchronized (sibling) {
        if (sibling.readBuffer == null) return;

        if (sibling.readLength == sibling.readBuffer.length) {
          if (sibling.readOffset < sibling.readLength) {
            try {
              sibling.wait();
            } catch (InterruptedException e) {
              throw new InterruptedIOException(e.getMessage());
            }
          }
          sibling.readOffset = 0;
          sibling.readLength = 0;
        }

        if (sibling.readOffset == sibling.readLength) {
          sibling.readOffset = 0;
          sibling.readLength = 0;
        }

        if (sibling.readBuffer == null) return;

        int sublen = sibling.readBuffer.length - sibling.readLength;
        if (length < sublen) sublen = length;

        System.arraycopy(buf, offset, sibling.readBuffer, sibling.readLength, sublen);

        sibling.readLength += sublen;

        length -= sublen;
        offset += sublen;

        sibling.notifyAll();
      }
    }
  }