move char array caching to streams

This commit is contained in:
Shay Banon 2013-07-28 22:43:35 +02:00
parent da3b4a3bf0
commit 7590f9f8a5
2 changed files with 16 additions and 10 deletions

View File

@ -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;
}
}

View File

@ -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<SoftReference<char[]>> charCache = new ThreadLocal<SoftReference<char[]>>();
private static char[] charCache(int size) {
SoftReference<char[]> 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<char[]>(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;