opentelemetry-java-instrumentation icon indicating copy to clipboard operation
opentelemetry-java-instrumentation copied to clipboard

Possible global stall around WeakLockFreeCache ReferenceQueue in Java 21 virtual-thread + ThrowableProxy class-loading path (after #10747/#10881)

Open YaoYingLong opened this issue 7 months ago • 3 comments

Describe the bug

We are seeing a reproducible global stall in a Java 21 application after it has been running normally for some time under traffic with a custom javaagent distro based on opentelemetry-java-instrumentation.

This does not look like a classic application-level deadlock with two explicit user locks. In thread dumps captured from two independent instances, the only consistently contended lock is the internal ReentrantLock inside a single java.lang.ref.ReferenceQueue.

Once the stall happens, multiple unrelated threads pile up on that same lock, including:

  • Reference Handler
  • OpenTelemetry weak-ref-cleaner
  • business request threads
  • ForkJoinPool workers / virtual-thread related execution paths

Another notable symptom is that the process often resumes immediately after running:

jcmd <pid> Thread.dump_to_file -format=text <file>

So this looks more like a pathological stall around the ReferenceQueue lock / scheduler interaction than a normal user-code lock cycle.

Steps to reproduce

We do not yet have a minimized standalone reproducer, but the production behavior is consistently observed with the following setup:

  1. Run a Tomcat-based Java application on JDK 21.0.5+11-LTS.

  2. Start the application with a custom javaagent distro based on opentelemetry-java-instrumentation.

  3. Use business code that submits async work through Executors.newVirtualThreadPerTaskExecutor().

  4. Under traffic, trigger exceptions that are logged with a real Throwable, for example:

    LoggerUtils.warn(logger, "[Pricing-Biz] normalPricing failed", e);
    
  5. After the application has been running for some time, the process enters a global stall where multiple threads block on the same ReferenceQueue internal lock.

  6. Capturing a thread dump with jcmd Thread.dump_to_file often causes the process to resume.

Expected behavior

I would expect none of the following to happen:

  • class-loading / helper-injection paths to globally stall on a single ReferenceQueue lock
  • virtual-thread continuation submission to get stuck behind the same lock
  • JDK Reference Handler, OTel weak-ref-cleaner, and business threads to all pile up on the same internal ReferenceQueue lock
  • a thread dump command to "unstick" the process

Actual behavior

The process enters a deadlock-like global stall.

Thread dumps from two separate instances show all of the following waiting on the same ReferenceQueue internal ReentrantLock:

  • Reference Handler
  • OpenTelemetry weak-ref-cleaner
  • business threads submitting or executing tasks
  • ForkJoinPool workers / virtual-thread related paths

Representative blocked paths include:

  1. Virtual-thread / logging / ThrowableProxy path
java.lang.VirtualThread.park
java.util.concurrent.locks.LockSupport.park
java.util.concurrent.locks.ReentrantLock.lock
java.lang.ref.ReferenceQueue.poll
io.opentelemetry...AbstractWeakConcurrentMap.expungeStaleEntries
io.opentelemetry...WeakConcurrentMap$WithInlinedExpunction.getIfPresent
io.opentelemetry...WeakLockFreeCache.get
io.opentelemetry.javaagent.tooling.HelperInjector.loadHelperClass
io.opentelemetry.javaagent.bootstrap.InjectedClassHelper.loadHelperClass
org.apache.catalina.loader.WebappClassLoaderBase.loadClass
org.apache.logging.log4j.core.impl.ThrowableProxyHelper.loadClass
org.apache.logging.log4j.core.impl.ThrowableProxyHelper.toExtendedStackTrace
org.apache.logging.log4j.core.impl.ThrowableProxy.<init>
org.apache.logging.log4j.core.pattern.ExtendedThrowablePatternConverter.format
org.apache.logging.slf4j.Log4jLogger.warn
com.ly.sof.utils.log.LoggerUtils.warn
  1. Virtual-thread continuation submission / transform path
java.util.concurrent.locks.ReentrantLock.lock
java.lang.ref.ReferenceQueue.poll
io.opentelemetry...AbstractWeakConcurrentMap.expungeStaleEntries
io.opentelemetry...WeakConcurrentMap$WithInlinedExpunction.getIfPresent
io.opentelemetry...WeakLockFreeCache.get
io.opentelemetry.javaagent.tooling.HelperInjector.isInjectedClass
io.opentelemetry.javaagent.tooling.AgentInstaller.lambda$configureIgnoredTypes$1
net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform
sun.instrument.InstrumentationImpl.transform
java.util.concurrent.ForkJoinTask.adapt
java.lang.VirtualThread.lazySubmitRunContinuation
  1. JDK reference processing waiting on the same lock
java.lang.ref.Reference$ReferenceHandler.run
java.lang.ref.Reference.processPendingReferences
java.lang.ref.Reference.enqueueFromPending
java.lang.ref.ReferenceQueue.enqueue
java.util.concurrent.locks.ReentrantLock.lock
  1. OpenTelemetry weak-ref cleaner waiting on the same lock
io.opentelemetry...AbstractWeakConcurrentMap.runCleanup
java.lang.ref.ReferenceQueue.remove
java.util.concurrent.locks.ReentrantLock.lock

Javaagent or library instrumentation version

Custom javaagent distro based on opentelemetry-java-instrumentation 1.31.0. The corresponding source tree already contains the virtual-thread related fix path associated with: - #10747 - #10854 - #10881 If needed, I can provide the exact upstream commit SHA used to build the custom distro.

Environment

JDK: 21.0.5+11-LTS

OS: Linux (inferred from deployment/runtime environment; exact distro can be provided if needed)

Runtime: Tomcat web application

Logging: Log4j2 2.23.1

The business application also uses Java 21 virtual threads directly via:

Executors.newVirtualThreadPerTaskExecutor()

Additional context

A few details that may be relevant:

  1. Even though our Log4j2 PatternLayout pattern is only %m%n, Log4j2 still renders exceptions implicitly because PatternLayout defaults alwaysWriteExceptions=true. As a result, logging a Throwable still goes through:

    • ExtendedThrowablePatternConverter
    • Log4jLogEvent.getThrownProxy()
    • ThrowableProxy
    • ThrowableProxyHelper.toExtendedStackTrace()
    • ThrowableProxyHelper.loadClass(...)
  2. Based on the corresponding source tree, the same global static ReferenceQueue in AbstractWeakConcurrentMap is used from at least two hot paths:

    • executor / virtual-field context attachment paths
    • helper-injector / class-loading / transform paths
  3. From the dumps, this issue does not appear to be just the already-known virtual-thread propagation path from #10747. We also see:

    • HelperInjector.isInjectedClass(...) -> WeakLockFreeCache.get(...)
    • HelperInjector.loadHelperClass(...) -> WeakLockFreeCache.get(...)

    during:

    • ThrowableProxyHelper.loadClass(...) while formatting exceptions
    • ForkJoinTask.adapt(...) from VirtualThread.lazySubmitRunContinuation(...)
  4. We have thread dumps from two independent instances showing the same pattern.

I can attach sanitized versions of:

  • thread_dump.txt
  • dump.txt
  • dump.json
  • thread_dump2.txt
  • dump2.txt
  • dump2.json

If maintainers think this is worth pursuing, I can also try to build a minimized reproducer focused on:

  • Java 21 virtual threads
  • exception logging with a real Throwable
  • ThrowableProxy class loading during stack-trace expansion
  • javaagent enabled

Tip

React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it. Learn more here.

YaoYingLong avatar Apr 15 '26 03:04 YaoYingLong

Reproducer would be ideal as this would let us get a better understanding of the issue and also allow for verifying whether whatever fix we come up with works. If a reproducer can't be built it would be good to know whether you can easily reproduce it or not so at least you could verify a potential fix. Given the limited information it is not really possible to tell whether this is something that only affects your custom agent or also the otel agent or whether it is caused by something in the otel agent, your agent, or an issue in the jdk. Do I understand it correctly that you see a bunch of threads waiting for a lock struck in java.lang.VirtualThread.park? Are there other threads that are waiting for the same lock struck in some other location like unsafe park? Is there a thread that holds the lock? When you take the stack trace does the app always resume? If so I guess the thread that was blocking others could have been already released by the time dump was taken and the dump might not show it. If you can easily reproduce it would it be possible to test with latest jdk 25 and see whether it also reproduces there?

laurit avatar Apr 16 '26 07:04 laurit

Reproducer would be ideal as this would let us get a better understanding of the issue and also allow for verifying whether whatever fix we come up with works. If a reproducer can't be built it would be good to know whether you can easily reproduce it or not so at least you could verify a potential fix. Given the limited information it is not really possible to tell whether this is something that only affects your custom agent or also the otel agent or whether it is caused by something in the otel agent, your agent, or an issue in the jdk. Do I understand it correctly that you see a bunch of threads waiting for a lock struck in java.lang.VirtualThread.park? Are there other threads that are waiting for the same lock struck in some other location like unsafe park? Is there a thread that holds the lock? When you take the stack trace does the app always resume? If so I guess the thread that was blocking others could have been already released by the time dump was taken and the dump might not show it. If you can easily reproduce it would it be possible to test with latest jdk 25 and see whether it also reproduces there?

@laurit The issue occurs sporadically; after the business code runs in the production environment for a period of time, there is a chance that it will appear, but it is relatively difficult to reproduce.

After obtaining the stack trace, the application does indeed recover and resume operation. Multiple problematic instances were tested, and all of them eventually returned to normal.

Based on the observed behavior, it seems that virtual thread switching may cause locks to not be released. Currently, during thread switching, class loading always uses VirtualField, which in turn calls WithInlinedExpunction's expungeStaleEntries, leading to a call to ReferenceQueue's poll method, resulting in lock contention. The contention frequency is particularly high in virtual thread scenarios.

Since there is already a weak-ref-cleaner thread for cleanup, why not consider applying the PR https://github.com/open-telemetry/opentelemetry-java-instrumentation/pull/10768 to the official release? This would greatly reduce lock contention.

YaoYingLong avatar Apr 21 '26 10:04 YaoYingLong

@laurit Thank you very much. I will apply this PR first and observe whether the deadlock issue occurs again.

YaoYingLong avatar Apr 22 '26 07:04 YaoYingLong