diff --git a/bramble-core/src/main/java/org/briarproject/bramble/mailbox/FeedableSyncInputStream.java b/bramble-core/src/main/java/org/briarproject/bramble/mailbox/FeedableSyncInputStream.java index 645be7191273e3686fc2c0005c29a2f17892f0f1..f7538c6e05e259c98b0f83558d7c5d09972988c8 100644 --- a/bramble-core/src/main/java/org/briarproject/bramble/mailbox/FeedableSyncInputStream.java +++ b/bramble-core/src/main/java/org/briarproject/bramble/mailbox/FeedableSyncInputStream.java @@ -8,12 +8,15 @@ import java.io.InputStream; public class FeedableSyncInputStream extends InputStream { private ByteArrayOutputStream os = new ByteArrayOutputStream(); private boolean isEOF = false; - private byte[] activeBuffer = null; - private int activeBufferPointer; + private byte[] activeBuffer = new byte[]{}; + private int activeBufferPointer = 0; @Override public synchronized int read() throws IOException { while (!hasBytes()) { + if(isEOF) + throw new EOFException(); + try { this.wait(); } catch (InterruptedException e) { @@ -21,31 +24,31 @@ public class FeedableSyncInputStream extends InputStream { } } - if (isEOF) - throw new EOFException(); - - if (activeBufferPointer >= activeBuffer.length) { - activeBuffer = os.toByteArray(); - activeBufferPointer = 0; - os.reset(); - } - return activeBuffer[activeBufferPointer++]; } private boolean hasBytes() { - return (activeBuffer != null && - activeBufferPointer < activeBuffer.length) || os.size() > 0; + // Check if active buffer has bytes left + if (activeBufferPointer < activeBuffer.length) + return true; + + // check if bytes from OS are available + if (os.size() <= 0) + return false; + + // update active buffer if bytes from OS are available + activeBuffer = os.toByteArray(); + os.reset(); + activeBufferPointer = 0; + return true; } public synchronized void feed(byte[] buffer) throws IOException { if (isEOF) throw new EOFException(); - if (activeBuffer == null) - activeBuffer = buffer; - os.write(buffer); + this.notifyAll(); }