Skip to content

Fix KryoSerializer ThreadLocal ClassLoader leak in web containers#353

Merged
hazendaz merged 2 commits intomasterfrom
copilot/review-issue-351
Mar 7, 2026
Merged

Fix KryoSerializer ThreadLocal ClassLoader leak in web containers#353
hazendaz merged 2 commits intomasterfrom
copilot/review-issue-351

Conversation

Copy link
Contributor

Copilot AI commented Mar 4, 2026

KryoSerializer holds a ThreadLocal<Kryo> on an enum singleton (effectively static) with no cleanup path. In containers like Tomcat that reuse threads across redeployments, this pins the WebappClassLoader via: Thread → ThreadLocalMap → Kryo → Kryo.class → WebappClassLoader, causing repeated OutOfMemoryError: Metaspace.

Changes

  • Serializer — adds a default void reset() no-op, giving callers a type-safe cleanup contract without breaking existing implementations.
  • KryoSerializer — overrides reset() to call kryos.remove(), severing the reference chain.
  • SerializerTestCase — adds testKryoResetClearsThreadLocal verifying reset() completes without error and the serializer remains fully functional afterward (lazy re-initialization).

Usage

Register a ServletContextListener and call reset() per worker thread on shutdown:

public void contextDestroyed(ServletContextEvent sce) {
    // call from each container thread, e.g. via an ExecutorService
    KryoSerializer.INSTANCE.reset();
}

Or use it generically through the Serializer interface if the concrete type is unknown:

Serializer serializer = redisConfig.getSerializer();
serializer.reset(); // no-op for JDKSerializer, removes ThreadLocal for KryoSerializer

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Add reset() default method to Serializer interface and implement it
in KryoSerializer to call kryos.remove(), preventing ClassLoader
pinning / Metaspace leaks in web-container environments.

Co-authored-by: hazendaz <975267+hazendaz@users.noreply.github.com>
Copilot AI changed the title [WIP] Review and propose fix for issue 351 Fix KryoSerializer ThreadLocal ClassLoader leak in web containers Mar 4, 2026
@coveralls
Copy link

coveralls commented Mar 7, 2026

Coverage Status

coverage: 82.915% (-0.2%) from 83.163%
when pulling 9624bef on copilot/review-issue-351
into 47da9d7 on master.

@hazendaz hazendaz marked this pull request as ready for review March 7, 2026 18:24
@hazendaz hazendaz merged commit 649760b into master Mar 7, 2026
16 of 18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants