Repository navigation
Description
Expected behavior
No memory leaks
Actual behavior
Memory is leaking in the presence of resizable thread pools
Steps to reproduce
Minimal yet complete reproducer code (or URL to code)
see below
(all reproducers were tested with -XX:MaxDirectMemorySize=1G)
Netty version
I'm using 4.1.63.Final in prod, but it is still reproducible for 4.1.80.Final too
JVM version (e.g. java -version)
openjdk version "15.0.7" 2022-04-19
OpenJDK Runtime Environment Zulu15.40+19-CA (build 15.0.7+4-MTS)
OpenJDK 64-Bit Server VM Zulu15.40+19-CA (build 15.0.7+4-MTS, mixed mode, sharing)
OS version (e.g. uname -a)
Linux hpple-l 5.11.0-41-generic #45~20.04.1-Ubuntu SMP Wed Nov 10 10:20:10 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
Hi!
I'm using Netty not only as a networking lib but as a general-purpose allocator as well.
In my case, buf allocations could be performed from any kind of thread pools: ELGs, ThreadPoolExecutors, FJPs.
Also, I'm using FastThreadLocalThread (via DefaultThreadFactory) for my own ThreadPoolExecutor pools to leverage the power of FastThreadLocals.
Unfortunately, it's not possible to do the same thing for FJP since it requires ForkJoinWorkerThreads to operate.
So, I've noticed that if the pool resizes over the time (like FJP that has a KeepAlive mechanism to shrink the pool if it hasn't been used for some time) then it could lead to unexpected memory leaks invisible to the current leak detector.
My first thoughts were like:
- What if some buffers outlive the thread which created them?
- On buffer release, underlying memory is always returned to the thread-local cache of the thread which did the allocation, no matter which thread deallocates
PooledByteBufholds a strong reference toPoolThreadCache- So, no finalizer will be called until the last buffer created by this thread is collected by GC
- When the allocating thread is not a
FastThreadLocalThread(e.g. FJP worker) noonRemovalwill be called either - No further allocations since the thread is terminated -> no internal trim (
freeSweepAllocationThreshold) - It's enough to have only one long living buffer to prevent the whole thread-local cache from returning memory to the related arena
There is the simple reproducer (important properties are set explicitly because different Netty versions may have different defaults):
public class NettyLeak0 {
public static void main(String[] args) {
System.setProperty("io.netty.allocator.useCacheForAllThreads", "true");
System.setProperty("io.netty.allocator.maxOrder", "9");
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
e.printStackTrace();
Runtime.getRuntime().halt(42);
});
var bufSize = 32 * 1024;
var longLiving = new AtomicInteger();
var longLivingSink = Collections.synchronizedList(new ArrayList<ByteBuf>());
for (int i = 0; true; i++) {
new Thread(() -> {
for (int x = 0; x < 256; x++) {
if (x != 0) {
// allocate different size classes to fill more thread caches
for (int j = 0; j <= 10; j++) {
ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer(bufSize >> j);
buf.release();
}
} else {
// only one buf is alive after thread termination
var buf = PooledByteBufAllocator.DEFAULT.directBuffer(1);
longLiving.incrementAndGet();
longLivingSink.add(buf);
}
}
}).start();
if (i % 1000 == 0) {
System.gc(); // to get a chance for io.netty.buffer.PoolThreadCache.finalize
System.out.println(PooledByteBufAllocator.DEFAULT.metric());
System.out.println(
"chunks count: " +
PooledByteBufAllocator.DEFAULT.metric().directArenas().stream()
.flatMap(m -> m.chunkLists().stream())
.mapToInt(m -> {
int count = 0;
for (var __ : m) {
count += 1;
}
return count;
})
.sum()
);
var ll = longLiving.get();
System.out.println("long living: " + ll);
// real size of a buf will be > 1b & < 1kb, but just estimate it as 1kb
System.out.println("long living size (MB): " + ll / 1024);
System.out.println();
}
}
}
}As far as I can see, there were several attempts to fix this problem in the past:
- a method to call directly: https://github.com/netty/netty/blame/4.1/buffer/src/main/java/io/netty/buffer/PooledByteBufAllocator.java#L499
- a global executor to perform a cleanup: ceffa82
- another kind of watcher: 085a61a#diff-2fbf82a7217a5ef66fbe8ff7ea653e1d802b14af03ce8d72863f8d66d057cf44
- object cleaner: e329ca1
- finalizer: Remove usage of ObjectCleaner #8064
Moreover, caching for user threads has already been disabled in latest releases: #12109
But, as I've already said, I'm using Netty as a general-purpose allocator, so io.netty.allocator.useCacheForAllThreads=false just does not fit.
So, initially, I've tried to use this deprecated freeThreadLocalCache method from PoolThreadCache on thread termination. But, it looks like it only makes things worse:
- It frees the cache and returns memory blocks acquired from already released buffers to the related arena
- What if we have some long living buffers that outlive the thread but actually being released during the application lifetime, just a bit later?
- Reclaimed memory of such long living buffers will be added to the cache after it has been freed
- Eventually, finalizer will come, but it will do nothing since
PoolThreadCache#freedwill be set totrue - So, those memory blocks will never be returned to any arena
Here is the reproducer:
public class NettyLeak1 {
public static void main(String[] args) {
System.setProperty("io.netty.allocator.useCacheForAllThreads", "true");
System.setProperty("io.netty.allocator.maxOrder", "9");
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
e.printStackTrace();
Runtime.getRuntime().halt(42);
});
var bufSize = 16 * 1024;
var longLiving = new AtomicInteger();
for (int i = 0; true; i++) {
new Thread(() -> {
for (int x = 0; x < 10; x++) {
ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer(bufSize);
if (x != 0) {
buf.release();
} else {
// release one buffer with delay, keeping some in-flight
longLiving.incrementAndGet();
CompletableFuture.runAsync(() -> {
buf.release();
longLiving.decrementAndGet();
}, delayedExecutor(5, TimeUnit.SECONDS));
}
}
// explicitly free before thread termination
PooledByteBufAllocator.DEFAULT.freeThreadLocalCache();
}).start();
if (i % 1000 == 0) {
System.gc(); // to ensure io.netty.buffer.PoolThreadCache.finalize
System.out.println(PooledByteBufAllocator.DEFAULT.metric());
System.out.println(
"chunks count: " +
PooledByteBufAllocator.DEFAULT.metric().directArenas().stream()
.flatMap(m -> m.chunkLists().stream())
.mapToInt(m -> {
int count = 0;
for (var __ : m) {
count += 1;
}
return count;
})
.sum()
);
var ll = longLiving.get();
System.out.println("long living: " + ll);
System.out.println("long living size (MB): " + ll * bufSize / 1024 / 1024);
System.out.println();
}
}
}
}Which means that this method is not only obsolete, but also is unsafe to use in current versions. Perhaps, it's worth mentioning this dangerous side-effect in javadoc.
So, my final workaround is a hacky double call to the trim method on thread termination (it works because a second call trims everything since there are no allocation stats between two consequent calls and trim does not interfere with finalizer):
public class NettyNoLeak1 {
public static void main(String[] args) {
System.setProperty("io.netty.allocator.useCacheForAllThreads", "true");
System.setProperty("io.netty.allocator.maxOrder", "9");
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
e.printStackTrace();
Runtime.getRuntime().halt(42);
});
var bufSize = 16 * 1024;
var longLiving = new AtomicInteger();
for (int i = 0; true; i++) {
new Thread(() -> {
for (int x = 0; x < 10; x++) {
ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer(bufSize);
if (x != 0) {
buf.release();
} else {
// release one buffer with delay, keeping some in-flight
longLiving.incrementAndGet();
CompletableFuture.runAsync(() -> {
buf.release();
longLiving.decrementAndGet();
}, delayedExecutor(5, TimeUnit.SECONDS));
}
}
// explicitly trim before thread termination
if (PooledByteBufAllocator.DEFAULT.trimCurrentThreadCache()) {
PooledByteBufAllocator.DEFAULT.trimCurrentThreadCache();
};
}).start();
if (i % 1000 == 0) {
System.gc(); // to ensure io.netty.buffer.PoolThreadCache.finalize
System.out.println(PooledByteBufAllocator.DEFAULT.metric());
System.out.println(
"chunks count: " +
PooledByteBufAllocator.DEFAULT.metric().directArenas().stream()
.flatMap(m -> m.chunkLists().stream())
.mapToInt(m -> {
int count = 0;
for (var __ : m) {
count += 1;
}
return count;
})
.sum()
);
var ll = longLiving.get();
System.out.println("long living: " + ll);
System.out.println("long living size (MB): " + ll * bufSize / 1024 / 1024);
System.out.println();
}
}
}
}Also, I suppose that if multiple ELGs are created and destroyed during the lifetime of application the same situation is possible too. In this case onRemoval will interfere with finalizer and prevent it from returning the memory of long living buffers.
What do you think about it after all?
Hypothetically, it could be fixed if PooledByteBuf does more checks over the current state of PoolThreadCache during the release.
E.g. it could return the memory directly to the arena if the cache is freed/freeing.
Activity
normanmaurer commentedon Sep 2, 2022
@chrisvest thoughts ?
chrisvest commentedon Sep 2, 2022
Definitely worth investigating. Wouldn't hold back 4.1.81 for it, though, since whatever is going on must have been an issue for a while.
horizonzy commentedon Oct 10, 2022
Nice catch.
Pool Thread Cache support memory leak check. (netty#12897)