From 7590f9f8a55cfb8bed5f22aa568a351768e14fb5 Mon Sep 17 00:00:00 2001 From: Shay Banon Date: Sun, 28 Jul 2013 22:43:35 +0200 Subject: [PATCH] move char array caching to streams --- .../common/io/stream/CachedStreamInput.java | 9 --------- .../common/io/stream/StreamInput.java | 17 ++++++++++++++++- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/elasticsearch/common/io/stream/CachedStreamInput.java b/src/main/java/org/elasticsearch/common/io/stream/CachedStreamInput.java index 894c0036251..b23cb6cde49 100644 --- a/src/main/java/org/elasticsearch/common/io/stream/CachedStreamInput.java +++ b/src/main/java/org/elasticsearch/common/io/stream/CachedStreamInput.java @@ -30,7 +30,6 @@ import java.lang.ref.SoftReference; public class CachedStreamInput { static class Entry { - char[] chars = new char[80]; final HandlesStreamInput handles; Entry(HandlesStreamInput handles) { @@ -70,12 +69,4 @@ public class CachedStreamInput { entry.handles.reset(compressor.streamInput(in)); return entry.handles; } - - public static char[] getCharArray(int size) { - Entry entry = instance(); - if (entry.chars.length < size) { - entry.chars = new char[size]; - } - return entry.chars; - } } diff --git a/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java b/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java index e2303017ca6..52bed6d85be 100644 --- a/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java +++ b/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java @@ -19,7 +19,9 @@ package org.elasticsearch.common.io.stream; +import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.BytesRef; +import org.apache.lucene.util.RamUsageEstimator; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; @@ -32,6 +34,7 @@ import org.joda.time.DateTime; import java.io.IOException; import java.io.InputStream; +import java.lang.ref.SoftReference; import java.util.*; /** @@ -39,6 +42,18 @@ import java.util.*; */ public abstract class StreamInput extends InputStream { + private static final ThreadLocal> charCache = new ThreadLocal>(); + + private static char[] charCache(int size) { + SoftReference ref = charCache.get(); + char[] arr = (ref == null) ? null : ref.get(); + if (arr == null || arr.length < size) { + arr = new char[ArrayUtil.oversize(size, RamUsageEstimator.NUM_BYTES_CHAR)]; + charCache.set(new SoftReference(arr)); + } + return arr; + } + private Version version = Version.CURRENT; public Version getVersion() { @@ -255,7 +270,7 @@ public abstract class StreamInput extends InputStream { public String readString() throws IOException { int charCount = readVInt(); - char[] chars = CachedStreamInput.getCharArray(charCount); + char[] chars = charCache(charCount); int c, charIndex = 0; while (charIndex < charCount) { c = readByte() & 0xff;