Class ReentrantLockDetector

java.lang.Object
se.deversity.asynctest.diagnostics.ReentrantLockDetector

public class ReentrantLockDetector extends Object
Detects ReentrantLock misuse patterns.

What it reports: a lock still held when the run is analysed by a thread that is no longer working (analyze()), and a starvation the lock itself corroborated (recordStarvation(ReentrantLock, String, long)). Those are the two things ReentrantLockDetector.ReentrantLockReport.hasIssues() gates on.

The held lock is asked of the lock itself: ReentrantLock.isLocked() on every lock this detector was told about, once the bodies have finished. A hold nobody gave back is what a lock() without its unlock() leaves behind, whether the missing release is an exception path with no finally or a helper that re-enters the lock and never releases the extra hold; either way every later caller parks in lock() for good. Recorded acquire and release counts cannot see the second shape, because the pair the caller instrumented is balanced; the lock can. The analysing thread's own holds are never reported.

A hold is a leak only if its holder has stopped working (#609). The lock names its holder only by name ("Locked by thread X"), and a name is not an identity: virtual threads are unnamed by default, so every one of them is "". So a hold is judged only when the name can be nobody but the thread last recorded acquiring the lock while holding it (recordLockAcquired(java.util.concurrent.locks.ReentrantLock, java.lang.String)): the name is not empty, it is that thread's, and no other live platform thread, nor any other live thread that recorded against the lock, carries it (#843, #848, #855). The hold is then reported when that thread has finished with the lock taken, or sits idle in a pool (ThreadPoolExecutor.getTask, ForkJoinPool.awaitWork), which is how a runner worker or an executor thread looks once the task that took the lock has ended. A recorded holder that is alive and anywhere else may still release the lock, so its hold is printed as context. So is every hold whose name identifies no one: an unnamed virtual thread, a name another live thread shares, or a thread that never recorded taking the lock, which, if it is virtual, no scan can list to see whether it is still running. The runner names its workers, so a worker that records its acquisition and ends holding the lock is reported. What remains is a virtual thread that never recorded against the lock and carries the recorded thread's non-empty name.

With the agent attached the holder is identified by the lock itself: the agent opens java.util.concurrent.locks to the library, which reads the owner Thread (#855). A hold whose owner has terminated, or sits idle in a pool, is reported whatever the thread is called, and one whose owner is still working is context; the name rules here and below apply only where the owner cannot be read.

An unidentified hold is context rather than a finding of any grade (#855), although it misses a real leak: a helper that re-enters the lock and keeps the extra hold on an unnamed virtual thread, or on a thread that never recorded taking the lock, balances the recorded counts, so LockLeakDetector has nothing to count either. A finding needs something correct code cannot show, and here nothing is left. The runner guarantees only that its own workers have finished when it analyses, and it names them; an unidentified holder is therefore a thread outside that guarantee, one the body or the code under test started and nobody has joined, which may legitimately still be working. For each shape the leak leaves exactly what correct code leaves: an unnamed thread that recorded its pair inside a hold it later gave back where nothing records, followed by another unnamed thread still working under the lock; or this run's worker, which registered the lock and ended without taking it, while a same-named worker of another run in parallel holds a shared lock. Even a FACT grade trips a failOn gate, and would then fail correct code whenever such a holder happened to be inside its critical section at analysis. Name the thread and record the acquisition, as the runner's workers do, and the hold is judged; a hold by a named thread that never recorded taking the lock says so in ReentrantLockDetector.ReentrantLockReport.notes(), which the runner logs on a clean run (#816).

What it records but does not report:

  • tryLock timeouts (recordLockTimeout(java.util.concurrent.locks.ReentrantLock)). A timeout is how a timed acquire says the lock was busy, and a caller that backs off on the false return has done the right thing. Only a caller that discards the return and runs the critical section unguarded is wrong, and that is invisible to a record call made after the fact; TRY_LOCK_MISUSE observes the use of the return value and is the detector for it (#589). Timeouts are printed as context, and a timed-out lock is also checked for a held lock at analysis, which is often what the timeout was a symptom of.
  • A recorded wait the lock did not corroborate (recordStarvation(String, long), or the lock overload with no barging seen). How long a thread waited is not evidence of starvation: a GC pause or a busy CI runner stretches every wait (#575), and a long queue behind a slow critical section is contention, not unfairness.
  • Acquire and release counts. An unbalanced pair is as likely to mean the two halves were instrumented in different places as it is to mean a hold was leaked. LockLeakDetector is the detector for that question, and since issue #368 this one forwards its registrations and records there whenever both are enabled, so a caller who instruments only these methods still gets the imbalance reported rather than silence. See deferLeakReportingTo(se.deversity.asynctest.diagnostics.LockLeakDetector). When the forwarded counts already show a leak on a lock, the held lock is left to that detector, so one leak is one finding.
  • Constructor Details

    • ReentrantLockDetector

      public ReentrantLockDetector()
  • Method Details

    • deferLeakReportingTo

      public void deferLeakReportingTo(@Nullable LockLeakDetector peer)
      Sends acquire and release records to peer, which is the detector that reports leaks.

      Called by DetectorRegistry when both detectors are enabled, as detectAll = true and the default Preset.ESSENTIALS both do. With no peer set this detector's own behaviour is unchanged.

      Parameters:
      peer - the detector that will report lock leaks, or null to forward nothing
    • registerLock

      public void registerLock(ReentrantLock lock, String name)
      Register a ReentrantLock for monitoring.
      Parameters:
      lock - the lock being recorded, tracked by identity rather than equality
      name - a label identifying the lock in the report
    • recordLockAcquired

      public void recordLockAcquired(ReentrantLock lock, String threadName)
      Record a successful lock acquisition.

      Call it while holding the lock, straight after acquiring. The lock is asked then which of the threads that recorded against it are still queued, which is how a thread passed over by another that barged ahead of it twice is seen (see recordStarvation(ReentrantLock, String, long)). The calling thread also becomes the lock's recorded holder until it records giving its last hold back, and a hold still taken at analysis is judged only for that thread, when it carries a non-empty name (see the class description).

      Parameters:
      lock - the lock being recorded, tracked by identity rather than equality
      threadName - a label identifying the thread in the report
    • recordLockReleased

      public void recordLockReleased(ReentrantLock lock, String threadName)
      Record a lock release.
      Parameters:
      lock - the lock being recorded, tracked by identity rather than equality
      threadName - a label identifying the thread in the report
    • recordLockTimeout

      public void recordLockTimeout(ReentrantLock lock)
      Record a tryLock that timed out.

      Context, not a finding: a timeout the caller handles is correct code, and whether the false return was discarded cannot be seen from here (TRY_LOCK_MISUSE can see it). The lock is remembered, printed with its timeout count, and checked at analysis for a hold nobody gave back, which is the finding a timeout is most often the symptom of.

      Parameters:
      lock - the lock being recorded, tracked by identity rather than equality
    • recordStarvation

      public void recordStarvation(String threadName, long waitTimeMs)
      Record a wait the caller took for starvation, with no lock to check it against.

      Context, not a finding (#608). Nothing here can ask a lock whether any thread was passed over, and a wait's length alone is not evidence: a GC pause or a busy CI runner stretches every wait (#575). Printed so the caller's observation is not lost; use recordStarvation(ReentrantLock, String, long) to have it judged. A wait of zero or less is not a wait, so it is ignored.

      Parameters:
      threadName - a label identifying the thread in the report
      waitTimeMs - how long the thread waited, in milliseconds; ignored unless positive
    • recordStarvation

      public void recordStarvation(ReentrantLock lock, String threadName, long waitTimeMs)
      Record a wait on lock that the caller took for starvation, to be judged against what the lock showed.

      Call it from the thread that waited, once it has the lock. It is a finding when this detector saw that thread passed over by a barger: another thread recorded acquiring the lock twice while this one stayed queued (ReentrantLock.hasQueuedThread(Thread) at each of that thread's recordLockAcquired(java.util.concurrent.locks.ReentrantLock, java.lang.String) calls). That is the mechanism of starvation on a ReentrantLock: a non-fair lock(), or an untimed tryLock() on any lock, takes a free lock ahead of the queue. A fair lock taken through lock() hands itself to the longest waiter, so the same load there is never a finding. A wait with no barging seen is printed as context: its length alone is not evidence (#575). No duration threshold is applied. The waiting thread must have recorded against the lock (for example registerLock(java.util.concurrent.locks.ReentrantLock, java.lang.String)) before it queued, so that the barger's records can ask about it.

      Parameters:
      lock - the lock the thread waited for, tracked by identity rather than equality
      threadName - a label identifying the thread in the report
      waitTimeMs - how long the thread waited, in milliseconds; ignored unless positive
      Since:
      1.12.1
    • analyze

      Analyze lock usage and return report.

      Reads each known lock's state now, so call it once the threads that used the locks have finished; the runner does.

      Returns:
      the findings this detector collected during the run