diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/common/io/stream/BytesStreamOutput.java b/modules/elasticsearch/src/main/java/org/elasticsearch/common/io/stream/BytesStreamOutput.java index 14b63c0e347..776931cb8c6 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/common/io/stream/BytesStreamOutput.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/common/io/stream/BytesStreamOutput.java @@ -34,15 +34,21 @@ public class BytesStreamOutput extends StreamOutput { */ public static class Cached { - private static final ThreadLocal> cache = new ThreadLocal>() { - @Override protected ThreadLocals.CleanableValue initialValue() { - return new ThreadLocals.CleanableValue(new BytesStreamOutput()); - } - }; + static class Entry { + final BytesStreamOutput bytes; + final HandlesStreamOutput handles; - private static final ThreadLocal> cacheHandles = new ThreadLocal>() { - @Override protected ThreadLocals.CleanableValue initialValue() { - return new ThreadLocals.CleanableValue(new HandlesStreamOutput(new BytesStreamOutput())); + Entry(BytesStreamOutput bytes, HandlesStreamOutput handles) { + this.bytes = bytes; + this.handles = handles; + } + } + + private static final ThreadLocal> cache = new ThreadLocal>() { + @Override protected ThreadLocals.CleanableValue initialValue() { + BytesStreamOutput bytes = new BytesStreamOutput(); + HandlesStreamOutput handles = new HandlesStreamOutput(bytes); + return new ThreadLocals.CleanableValue(new Entry(bytes, handles)); } }; @@ -50,13 +56,13 @@ public class BytesStreamOutput extends StreamOutput { * Returns the cached thread local byte stream, with its internal stream cleared. */ public static BytesStreamOutput cached() { - BytesStreamOutput os = cache.get().get(); + BytesStreamOutput os = cache.get().get().bytes; os.reset(); return os; } public static HandlesStreamOutput cachedHandles() throws IOException { - HandlesStreamOutput os = cacheHandles.get().get(); + HandlesStreamOutput os = cache.get().get().handles; os.reset(); return os; }