From 370e7872ad8f7cd2b520a1a1f61591eab449389c Mon Sep 17 00:00:00 2001 From: Mikhail Bobrutskov Date: Sun, 15 Oct 2023 22:51:42 +0200 Subject: [PATCH] fix for stackoverflow when low on memory and created array removed immediately --- .../wizzardo/http/ReadableByteArrayPool.java | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/wizzardo/http/ReadableByteArrayPool.java b/src/main/java/com/wizzardo/http/ReadableByteArrayPool.java index 72118d6..68d4303 100644 --- a/src/main/java/com/wizzardo/http/ReadableByteArrayPool.java +++ b/src/main/java/com/wizzardo/http/ReadableByteArrayPool.java @@ -10,19 +10,24 @@ * Created by wizzardo on 26/05/16. */ public class ReadableByteArrayPool { - private static Pool pool = new PoolBuilder() + private static final Pool pool = new PoolBuilder() .queue(PoolBuilder.createThreadLocalQueueSupplier()) .supplier(() -> new PooledReadableByteArray(new byte[10240])) - .holder((pool, value) -> value.holder = new SoftHolder<>(pool, value)) + .holder(SoftHolder::new) .resetter(PooledReadableByteArray::reset) .build(); - private static class SoftHolder implements Holder { + public interface WithHolder { + void setHolder(Holder holder); + } + + private static class SoftHolder> implements Holder { final Pool pool; volatile SoftReference ref; private SoftHolder(Pool pool, T value) { this.pool = pool; + value.setHolder(this); ref = new SoftReference<>(value); } @@ -30,7 +35,13 @@ private SoftHolder(Pool pool, T value) { public T get() { T value = ref.get(); if (value == null) { - return pool.holder().get(); + if (pool.size() > 0) + return pool.holder().get(); + else { + T t = pool.create(); + new SoftHolder<>(pool, t); + return t; + } } else { pool.reset(value); } @@ -43,7 +54,7 @@ public void close() { } } - public static class PooledReadableByteArray extends ReadableByteArray { + public static class PooledReadableByteArray extends ReadableByteArray implements WithHolder{ private volatile Holder holder; PooledReadableByteArray(byte[] bytes) { @@ -67,6 +78,11 @@ public void reset() { length = bytes.length; position = 0; } + + @Override + public void setHolder(Holder holder) { + this.holder = holder; + } } public static PooledReadableByteArray get() {