Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ abstract class StringCodecBase implements Codec<String> {
private final Charset charset;
private final boolean fixedLength;
private final int maxBytesPerChar;
// CharsetEncoder/CharsetDecoder are stateful and not thread-safe: reuse one per thread.
private final ThreadLocal<CharsetEncoder> threadLocalEncoder = ThreadLocal.withInitial(this::newEncoder);
private final ThreadLocal<CharsetDecoder> threadLocalDecoder = ThreadLocal.withInitial(this::newDecoder);

StringCodecBase(Charset charset) {
this.charset = charset;
Expand Down Expand Up @@ -97,7 +100,7 @@ private int getSerializedSizeUpperBound(String s) {
private <E extends Exception> PutToByteBuffer<E> encode(
String string, Integer serializedSize, Function<String, E> newE) {
return buffer -> {
final CoderResult result = newEncoder().encode(
final CoderResult result = threadLocalEncoder.get().reset().encode(
CharBuffer.wrap(string), buffer, true);
if (result.isError()) {
throw newE.apply("Failed to encode with " + charset + ": " + result
Expand All @@ -114,7 +117,7 @@ private <E extends Exception> PutToByteBuffer<E> encode(

String decodeNoFallback(ByteBuffer buffer) throws CodecException {
try {
return newDecoder().decode(buffer.asReadOnlyBuffer()).toString();
return threadLocalDecoder.get().decode(buffer.asReadOnlyBuffer()).toString();
} catch (Exception e) {
throw new CodecException("Failed to decode " + buffer, e);
}
Expand All @@ -123,7 +126,7 @@ String decodeNoFallback(ByteBuffer buffer) throws CodecException {
String decodeWithFallback(ByteBuffer buffer) {
Runnable error = null;
try {
return newDecoder().decode(buffer.asReadOnlyBuffer()).toString();
return threadLocalDecoder.get().decode(buffer.asReadOnlyBuffer()).toString();
} catch (Exception e) {
error = () -> LOG.warn("Failed to decode buffer with {}, buffer = (hex) {}",
charset, StringUtils.bytes2Hex(buffer, 20), e);
Expand Down
Loading