From 09e6d003cbe194778ac322e248ba30438a30bb68 Mon Sep 17 00:00:00 2001 From: Ben Gruver Date: Sun, 21 Oct 2012 21:09:00 -0700 Subject: [PATCH] Use thread local storage for the temporary buffer in Utf8Utils --- util/src/main/java/org/jf/util/Utf8Utils.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/util/src/main/java/org/jf/util/Utf8Utils.java b/util/src/main/java/org/jf/util/Utf8Utils.java index a6d1f0b4..479fd2fc 100644 --- a/util/src/main/java/org/jf/util/Utf8Utils.java +++ b/util/src/main/java/org/jf/util/Utf8Utils.java @@ -65,23 +65,28 @@ public final class Utf8Utils { return result; } - private static char[] tempBuffer = null; + private static final ThreadLocal localBuffer = + new ThreadLocal () { + @Override protected char[] initialValue() { + // A reasonably sized initial value + return new char[256]; + } + }; /** * Converts an array of UTF-8 bytes into a string. * - * This method uses a global buffer to avoid having to allocate one every time, so it is *not* thread-safe - * * @param bytes non-null; the bytes to convert * @param start the start index of the utf8 string to convert * @param length the length of the utf8 string to convert, not including any null-terminator that might be present * @return non-null; the converted string */ public static String utf8BytesToString(byte[] bytes, int start, int length) { - if (tempBuffer == null || tempBuffer.length < length) { - tempBuffer = new char[length]; + char[] chars = localBuffer.get(); + if (chars == null || chars.length < length) { + chars = new char[length]; + localBuffer.set(chars); } - char[] chars = tempBuffer; int outAt = 0; for (int at = start; length > 0; /*at*/) {