share cached bytes

This commit is contained in:
kimchy 2010-05-09 20:11:54 +03:00
parent 3e405c3ec7
commit 7fe5243517
3 changed files with 12 additions and 18 deletions

View File

@ -24,6 +24,12 @@ package org.elasticsearch.util;
*/
public class Bytes {
public static ThreadLocal<ThreadLocals.CleanableValue<byte[]>> cachedBytes = new ThreadLocal<ThreadLocals.CleanableValue<byte[]>>() {
@Override protected ThreadLocals.CleanableValue<byte[]> initialValue() {
return new ThreadLocals.CleanableValue<byte[]>(new byte[256]);
}
};
public static final byte[] EMPTY_ARRAY = new byte[0];

View File

@ -19,7 +19,7 @@
package org.elasticsearch.util.io.stream;
import org.elasticsearch.util.ThreadLocals;
import org.elasticsearch.util.Bytes;
import org.elasticsearch.util.Unicode;
import java.io.EOFException;
@ -31,12 +31,6 @@ import java.io.InputStream;
*/
public abstract class StreamInput extends InputStream {
private static ThreadLocal<ThreadLocals.CleanableValue<byte[]>> cachedBytes = new ThreadLocal<ThreadLocals.CleanableValue<byte[]>>() {
@Override protected ThreadLocals.CleanableValue<byte[]> initialValue() {
return new ThreadLocals.CleanableValue<byte[]>(new byte[256]);
}
};
/**
* Reads and returns a single byte.
*/
@ -109,10 +103,10 @@ public abstract class StreamInput extends InputStream {
*/
public String readUTF() throws IOException {
int length = readVInt();
byte[] bytes = cachedBytes.get().get();
byte[] bytes = Bytes.cachedBytes.get().get();
if (bytes == null || length > bytes.length) {
bytes = new byte[(int) (length * 1.25)];
cachedBytes.get().set(bytes);
Bytes.cachedBytes.get().set(bytes);
}
readBytes(bytes, 0, length);
return Unicode.fromBytes(bytes, 0, length);

View File

@ -20,7 +20,7 @@
package org.elasticsearch.util.xcontent.xson;
import org.apache.lucene.util.StringHelper;
import org.elasticsearch.util.ThreadLocals;
import org.elasticsearch.util.Bytes;
import org.elasticsearch.util.Unicode;
import org.elasticsearch.util.xcontent.XContentType;
import org.elasticsearch.util.xcontent.support.AbstractXContentParser;
@ -34,12 +34,6 @@ import java.io.InputStream;
*/
public class XsonXContentParser extends AbstractXContentParser {
private static ThreadLocal<ThreadLocals.CleanableValue<byte[]>> cachedBytes = new ThreadLocal<ThreadLocals.CleanableValue<byte[]>>() {
@Override protected ThreadLocals.CleanableValue<byte[]> initialValue() {
return new ThreadLocals.CleanableValue<byte[]>(new byte[256]);
}
};
private final InputStream is;
private Token currentToken;
@ -350,10 +344,10 @@ public class XsonXContentParser extends AbstractXContentParser {
*/
private void inUtf16() throws IOException {
int length = inVInt();
byte[] bytes = cachedBytes.get().get();
byte[] bytes = Bytes.cachedBytes.get().get();
if (bytes == null || length > bytes.length) {
bytes = new byte[(int) (length * 1.25)];
cachedBytes.get().set(bytes);
Bytes.cachedBytes.get().set(bytes);
}
inBytes(bytes, 0, length);
utf16Result = Unicode.fromBytesAsUtf16(bytes, 0, length);