GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Aggressively remove PoolThreadCache references from its finalizer object by franz1981 · Pull Request #14155 · netty/netty

Conversation

@franz1981

@franz1981 franz1981 commented Jul 2, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Motivation:
If a cache's FastThreadLocalThread owner win the race to remove the cache, due to debugging capabilities, its finalizer will still retain a strong reference to it, causing few classes to leak (and eventually, their ClassLoader). Despite we cannot avoid finalizers to wait the finalization pass, we can reduce the memory footprint of "leaked" instances before the finalization happen.

Modification:
non-debug early cache removal can remove the cache strong reference within FreeOnFinalize, making it an emtpy shell, eligible for GC.

Result:
Smaller memory footprint while waiting finalization to happen

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

He-Pin and huibinliupush reacted with thumbs up emoji
All reactions
  • 👍 2 reactions
@franz1981 franz1981 added the improvement label Jul 2, 2024
@franz1981
franz1981 requested review from chrisvest and normanmaurer July 2, 2024 12:26
@franz1981

franz1981 commented Jul 2, 2024

Copy link
Copy Markdown
Contributor Author

This is related quarkusio/quarkus#41607 and quarkusio/quarkus#41156 (comment)

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981

franz1981 commented Jul 2, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor Author

@normanmaurer @chrisvest It would be great if we could just let FastThreadLocalThread which cleanupFastThreadLocals == true to not use any finalizer, trusting them, but maybe I'm making this too simple and there's still a reason to use finalizers for those, wdyt?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981

franz1981 commented Jul 2, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor Author

FYI @normanmaurer @chrisvest I've added 72c4731b0b767cfb1864c60a757944fd1bb2450a which push the approach further by enabling opt-in to NOT use finalizers for FastThreadLocalThreads which take care of cleaning up their FastThreadLocals instances.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981 franz1981 mentioned this pull request Jul 2, 2024
Netty finalizers load classes from closed class loaders quarkusio/quarkus#41607
Closed
@franz1981
franz1981 force-pushed the 4.1_classloader_leak branch from 0850f3e to 72c4731 Compare July 2, 2024 13:29
normanmaurer
normanmaurer requested changes Jul 2, 2024
View reviewed changes
Comment thread buffer/src/main/java/io/netty/buffer/PoolThreadCache.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread buffer/src/main/java/io/netty/buffer/PoolThreadCache.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

chrisvest
chrisvest reviewed Jul 2, 2024
View reviewed changes

@chrisvest chrisvest left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran the non-broken NettyLeak1 reproducer from #12749, and it looks like the issue is resolved. So… controversial suggestion: maybe we don't need to make the leak check and can always clear the FreeOnFinalize.cache field.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

franz1981 reacted with heart emoji
All reactions
  • ❤️ 1 reaction
Comment thread buffer/src/main/java/io/netty/buffer/PoolThreadCache.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

@chrisvest

chrisvest commented Jul 2, 2024

Copy link
Copy Markdown
Member

Here's a fixed version of NettyLeak0 from #12749 which also shows no leaks:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class NettyLeak0 {

    public static void main(String[] args) throws Exception {
        System.setProperty("io.netty.allocator.useCacheForAllThreads", "true");
        System.setProperty("io.netty.allocator.maxOrder", "9");
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            e.printStackTrace();
            Runtime.getRuntime().halt(42);
        });

        int bufSize = 32 * 1024;

        AtomicInteger longLiving = new AtomicInteger();
        List<ByteBuf> longLivingSink = Collections.synchronizedList(new ArrayList<ByteBuf>());
        ArrayBlockingQueue<Thread> threads = new ArrayBlockingQueue<>(64);
        for (int i = 0; true; i++) {
            Thread thread = 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
                        ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer(1);
                        longLiving.incrementAndGet();
                        longLivingSink.add(buf);
                    }
                }
            });
            if (!threads.offer(thread)) {
                threads.take().join();
                threads.put(thread);
            }
            thread.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 (PoolChunkMetric __ : m) {
                                                count += 1;
                                            }
                                            return count;
                                        })
                                        .sum()
                );
                int 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();
                longLivingSink.removeIf(buf -> buf.release() && decrement(longLiving));
            }
        }
    }

    private static boolean decrement(AtomicInteger longLiving) {
        longLiving.addAndGet(-1);
        return true;
    }
}
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981

franz1981 commented Jul 3, 2024

Copy link
Copy Markdown
Contributor Author

@normanmaurer wdyt about the @chrisvest suggestion?

maybe we don't need to make the leak check and can always clear the FreeOnFinalize.cache field.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Jul 3, 2024

Copy link
Copy Markdown
Member

@normanmaurer wdyt about the @chrisvest suggestion?

maybe we don't need to make the leak check and can always clear the FreeOnFinalize.cache field.

Sounds good to me

franz1981 reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981
franz1981 marked this pull request as ready for review July 4, 2024 09:58
@franz1981

franz1981 commented Jul 4, 2024

Copy link
Copy Markdown
Contributor Author

PTAL @chrisvest @normanmaurer

Not very happy that I've added a new sys prop here, but I want to keep it safe for existing users...
Who requires to keep on creating/stopping event loop threads (e.g. the dev mode in quarkus) can decide to avoid finalization and just set it to speedup dropping the previous classloader (@gsmet please try this for your issue)

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981
franz1981 force-pushed the 4.1_classloader_leak branch from 14cbf9d to 9375b45 Compare July 4, 2024 10:01
@normanmaurer

normanmaurer commented Jul 4, 2024

Copy link
Copy Markdown
Member

PTAL @chrisvest @normanmaurer

Not very happy that I've added a new sys prop here, but I want to keep it safe for existing users... Who requires to keep on creating/stopping event loop threads (e.g. the dev mode in quarkus) can decide to avoid finalization and just set it to speedup dropping the previous classloader (@gsmet please try this for your issue)

That's good to me

franz1981 reacted with rocket emoji
All reactions
  • 🚀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981
Aggressively remove PoolThreadCache references from its finalizer object
f618686
Motivation:
If a cache's FastThreadLocalThread owner win the race to remove the cache, due to debugging
capabilities, it's finalizer will still retain a strong reference to it, causing few classes to leak (and eventually, their ClassLoader).
Despite we cannot avoid finalizers to wait the finalization pass, we can reduce the memory footprint of "leaked" instances before the finalization happen.

Modification:
non-debug early cache removal can remove the cache strong reference within FreeOnFinalize, making it an emtpy shell, eligible for GC.

Result:
Smaller memory footprint while waiting finalization to happen
@franz1981
franz1981 force-pushed the 4.1_classloader_leak branch from 9375b45 to f618686 Compare July 4, 2024 10:53
normanmaurer
normanmaurer approved these changes Jul 4, 2024
View reviewed changes
@franz1981

franz1981 commented Jul 4, 2024

Copy link
Copy Markdown
Contributor Author

Let's see what the CI think @normanmaurer and thanks again!

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@gsmet

gsmet commented Jul 4, 2024

Copy link
Copy Markdown
Contributor

Let me have a look for my use case before merging. Thanks!

franz1981 reacted with rocket emoji
All reactions
  • 🚀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@gsmet

gsmet commented Jul 4, 2024

Copy link
Copy Markdown
Contributor

I can confirm that I don't see the finalizers trying to load classes after my CL is closed, which looks promising!

franz1981 reacted with heart emoji
All reactions
  • ❤️ 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

gsmet added a commit to gsmet/quarkus that referenced this pull request Jul 4, 2024
@gsmet
Enable io.netty.allocator.disableCacheFinalizersForFastThreadLocalThr…
4a2ebe9
…eads

This is going to be useful once
netty/netty#14155 lands in Quarkus.
@gsmet gsmet mentioned this pull request Jul 4, 2024
Enable io.netty.allocator.disableCacheFinalizersForFastThreadLocalThreads quarkusio/quarkus#41686
Merged
@franz1981

franz1981 commented Jul 4, 2024

Copy link
Copy Markdown
Contributor Author

So @normanmaurer , now just need CI and @chrisvest to be happy bout this

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981

franz1981 commented Jul 8, 2024

Copy link
Copy Markdown
Contributor Author

Windows seems the only one unhappy, likely for unrelated reasons; if you are good to go, I am done here @normanmaurer

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Jul 8, 2024

Copy link
Copy Markdown
Member

I am happy if @chrisvest is happy... @chrisvest PTAL again

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

chrisvest
chrisvest approved these changes Jul 8, 2024
View reviewed changes

@chrisvest chrisvest left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

franz1981 reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
@franz1981

franz1981 commented Jul 9, 2024

Copy link
Copy Markdown
Contributor Author

@normanmaurer I can merge it myself, ok @normanmaurer ?
My first time merging a PR here (no jokes!)

chrisvest reacted with hooray emoji
All reactions
  • 🎉 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Jul 9, 2024

Copy link
Copy Markdown
Member

@franz1981 sure... lets go. Please also cherry-pick it to the other related branches..

franz1981 reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer normanmaurer added this to the 4.1.112.Final milestone Jul 9, 2024
@franz1981
franz1981 merged commit 8039232 into netty:4.1 Jul 9, 2024
franz1981 added a commit that referenced this pull request Jul 9, 2024
@franz1981
Aggressively remove PoolThreadCache references from its finalizer obj…
7a261ac
…ect (#14155)

Motivation:
If a cache's FastThreadLocalThread owner win the race to remove the
cache, due to debugging capabilities, its finalizer will still retain a
strong reference to it, causing few classes to leak (and eventually,
their ClassLoader). Despite we cannot avoid finalizers to wait the
finalization pass, we can reduce the memory footprint of "leaked"
instances before the finalization happen.

Modification:
non-debug early cache removal can remove the cache strong reference
within FreeOnFinalize, making it an emtpy shell, eligible for GC.

Result:
Smaller memory footprint while waiting finalization to happen
@huibinliupush

huibinliupush commented Sep 6, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

@normanmaurer @chrisvest It would be great if we could just let FastThreadLocalThread which cleanupFastThreadLocals == true to not use any finalizer, trusting them, but maybe I'm making this too simple and there's still a reason to use finalizers for those, wdyt?

hi @franz1981 , would you please tell me the reason why FastThreadLocalThread(cleanupFastThreadLocals == true) must use finalizer to clean their PoolThreadCache ?

    private static boolean useCacheFinalizers(Thread current) {
        if (!defaultDisableCacheFinalizersForFastThreadLocalThreads()) {
            return true;
        }
        // why  FastThreadLocalThread(cleanupFastThreadLocals == true) must use finalizer ?
        return current instanceof FastThreadLocalThread &&
               ((FastThreadLocalThread) current).willCleanupFastThreadLocals();
    }

In my opinion, when the FastThreadLocalThread(cleanupFastThreadLocals == true) exits, FastThreadLocal.removeAll() will be called, and in the onRemoval method of PoolThreadLocalCache, the PoolThreadCache will be freed . there is no need to use any finalizer 。

        @Override
        protected void onRemoval(PoolThreadCache threadCache) {
            threadCache.free(false);
        }

Why can't we just do this?

    private static boolean useCacheFinalizers() {
       return !defaultDisableCacheFinalizersForFastThreadLocalThreads();
    }
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

gsmet added a commit to gsmet/quarkus that referenced this pull request Jan 7, 2025
@gsmet
Enable io.netty.allocator.disableCacheFinalizersForFastThreadLocalThr…
4c45615
…eads

This is going to be useful once
netty/netty#14155 lands in Quarkus.
gsmet added a commit to gsmet/quarkus that referenced this pull request Jan 16, 2025
@gsmet
Enable io.netty.allocator.disableCacheFinalizersForFastThreadLocalThr…
7d664bd
…eads

This is going to be useful once
netty/netty#14155 lands in Quarkus.
carlesarnal pushed a commit to carlesarnal/quarkus that referenced this pull request Feb 6, 2025
@gsmet @carlesarnal
Enable io.netty.allocator.disableCacheFinalizersForFastThreadLocalThr…
d36607e
…eads

This is going to be useful once
netty/netty#14155 lands in Quarkus.
lasteris pushed a commit to lasteris/quarkus that referenced this pull request Sep 12, 2025
@gsmet @lasteris
Enable io.netty.allocator.disableCacheFinalizersForFastThreadLocalThr…
93c50f2
…eads

This is going to be useful once
netty/netty#14155 lands in Quarkus.
This was referenced Sep 14, 2026
Http2: Reserve promised stream for PUSH_PROMISE after local RST_STREAM #17471
Closed
cache failure 1233e4a5 #17565
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@chrisvest chrisvest chrisvest approved these changes
@normanmaurer normanmaurer normanmaurer approved these changes

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

improvement

Projects

None yet

Milestone

4.1.112.Final

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

5 participants

@franz1981 @chrisvest @normanmaurer @gsmet @huibinliupush
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.