Make LineBufferedOutputStream resistant to exceptions thrown while flushing its buffer.
--
MOS_MIGRATED_REVID=139771073
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/LineBufferedOutputStream.java b/src/main/java/com/google/devtools/build/lib/runtime/LineBufferedOutputStream.java
index 3d0c44f..b4f3b85 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/LineBufferedOutputStream.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/LineBufferedOutputStream.java
@@ -36,13 +36,19 @@
this.pos = 0;
}
+ private void flushBuffer() throws IOException {
+ int oldPos = pos;
+ // Set pos to zero first so that if the write below throws, we are still in a consistent state.
+ pos = 0;
+ wrapped.write(buffer, 0, oldPos);
+ }
+
@Override
public synchronized void write(byte[] b, int off, int inlen) throws IOException {
if (inlen > buffer.length * 2) {
// Do not buffer large writes
if (pos > 0) {
- wrapped.write(buffer, 0, pos);
- pos = 0;
+ flushBuffer();
}
wrapped.write(b, off, inlen);
return;
@@ -51,14 +57,8 @@
int next = off;
while (next < off + inlen) {
buffer[pos++] = b[next];
- if (b[next] == '\n') {
- wrapped.write(buffer, 0, pos);
- pos = 0;
- }
-
- if (pos == buffer.length) {
- wrapped.write(buffer, 0, pos);
- pos = 0;
+ if (b[next] == '\n' || pos == buffer.length) {
+ flushBuffer();
}
next++;