Skip to content

Read-Write Lock Deadlock while fetching references in LSPUsageSearcher #1566

Closed

Description

@SergejSalnikov

This is a classic Read-Write Lock Deadlock involving the IntelliJ Read Lock. The deadlock occurs because a background thread is blocking while holding the IntelliJ Read Lock, waiting for an asynchronous computation (LSP response mapping) that itself needs to acquire the Read Lock to finish.

Here is the detailed analysis of the threads involved, the deadlock cycle, and how to fix it.


1. The Three Key Players in the Deadlock

Player A: ApplicationImpl pooled thread 96 (Find Usages Execution)

  • State: TIMED_WAITING (blocking on a CompletableFuture.get()).
  • What it did:
    1. Entered a ReadAction at LSPUsageSearcher.java:L62:
      ReadAction.run(() -> { ... })
    2. Dispatched the asynchronous usagesFuture (sending textDocument/references request to the server).
    3. Blocked itself inside the active ReadAction by calling waitUntilDone(usagesFuture) at LSPUsageSearcher.java:L106.
  • Status: Holds the IntelliJ Read Lock and refuses to release it until usagesFuture completes.

Player B: JobScheduler FJ pool 2/13 (LSP4J Message Receiver & Processor)

  • State: WAITING (waiting to acquire a Read Lock permit).
  • What it did:
    1. Asynchronously received the server's JSON-RPC response.
    2. Triggered the future completion chain: RemoteEndpoint.handleResponse -> LSPUsageSupport.createUsages -> LSPUsagesManager.toPsiElement -> LSPPsiElementFactory.toPsiElement.
    3. At LSPPsiElementFactory.toPsiElement(LSPPsiElementFactory.java:76), it attempted to acquire the IntelliJ Read Lock (ReadAction.compute) to safely construct and resolve the target PSI elements.
  • Status: Blocked indefinitely trying to acquire the Read Lock.

Player C: AWT-EventQueue-0 (UI Event Dispatch Thread)

  • State: TIMED_WAITING (waiting on condition).
  • What it did:
    1. The user clicked the mouse (mousePressed event).
    2. The EDT attempted to acquire a Write Intent permit (runWriteIntentReadAction) to handle UI events.
    3. Because Player A is holding a Read Lock, the write request is queued and the EDT is suspended waiting for the read lock to clear.
  • Status: Blocked, preventing any new readers (like Player B) from acquiring the Read Lock (due to write-preference in lock scheduling).

2. The Deadlock Cycle

flowchart TD
    A[ApplicationImpl pooled thread 96 <br> Holds Read Lock] -->|Blocks waiting for future to complete| B[JobScheduler FJ pool 2/13 <br> Processing LSP Response]
    B -->|Requires Read Lock to parse PSI elements| A
    C[AWT-EventQueue-0 <br> Queued Write-Intent Lock] -->|Blocks new readers| B
Loading
  1. Thread 96 holds the Read Lock and is waiting for the future to complete.
  2. To complete the future, FJ pool 2/13 must resolve the coordinates to a PsiElement (which requires a Read Lock).
  3. FJ pool 2/13 cannot acquire the Read Lock because Thread 96 is holding it, and the EDT has queued a write request which blocks subsequent read requests.

3. The Root Cause

Acquiring a Read Lock, starting async work, and then blocking inside the Read Lock is a critical IntelliJ Threading Antipattern.

Because Read Actions are not reentrant across different threads, FJ pool 2/13 cannot borrow the read lock held by pooled thread 96. Since pooled thread 96 is blocked waiting for FJ pool 2/13, the lock is never released.


4. How to Fix It

You must ensure that no blocking operation (waitUntilDone / CompletableFuture.get()) is executed inside a ReadAction.

The Fix in LSPUsageSearcher.java:

Refactor processElementUsages so that the async lookup and wait are performed outside of any ReadAction, and only wrap the specific parts that require PSI/VFS access inside narrow read actions:

// LSPUsageSearcher.java
@Override
public void processElementUsages(@NotNull PsiElement element, @NotNull Processor<? super Usage> processor, @NotNull FindUsagesOptions options) {
    
    // 1. Collect only what we need from the element inside a narrow ReadAction
    Position position = ReadAction.compute(() -> getPosition(element, element.getContainingFile()));
    PsiFile file = ReadAction.compute(() -> element.getContainingFile());
    Project project = element.getProject();
    
    if (position == null || file == null) return;

    // 2. Dispatch the async LSP request OUTSIDE of the ReadAction
    LSPUsageSupport usageSupport = new LSPUsageSupport(file);
    LSPUsageSupport.LSPUsageSupportParams params = new LSPUsageSupport.LSPUsageSupportParams(position);
    CompletableFuture<List<LSPUsagePsiElement>> usagesFuture = usageSupport.getFeatureData(params);

    try {
        // 3. Wait for the future OUTSIDE of the ReadAction
        // This allows the ForkJoinPool background threads to freely acquire ReadActions
        // to resolve the PSI elements during mapping!
        waitUntilDone(usagesFuture); 
        
        if (usagesFuture.isDone()) {
            List<LSPUsagePsiElement> usages = usagesFuture.getNow(null);
            if (usages != null) {
                // 4. Process the results (requires ReadAction again for VFS/PSI mapping)
                ReadAction.run(() -> {
                    for (LSPUsagePsiElement usage : usages) {
                        processor.process(new UsageInfo2UsageAdapter(new UsageInfo(usage)));
                    }
                });
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error while collecting LSP Usages", e);
    }
}

Activity

  1. angelozerr commented on May 28, 2026

    @angelozerr
    Contributor

    Thanks for your detailled explanation!

    Is there any chance to have a PR?

  2. angelozerr commented on May 29, 2026

    @angelozerr
    Contributor

    @SergejSalnikov thanks so much for your relevant info.

    I will work on that before doing the release.

  3. sampaio96 commented on Jun 9, 2026

    @sampaio96

    I am experiencing this exact same Read-Write deadlock pattern, but in LSPDocumentLinkAnnotator.collectInformation. It is also calling CompletableFutures.waitUntilDone() while holding a ReadAction. Please ensure this file is refactored along with LSPUsageSearcher!

  4. angelozerr commented on Jun 9, 2026

    @angelozerr
    Contributor

    @sampaio96 you mean that LSPUsageSearcher should be fixed?

  5. added
    bug
    on Jun 9, 2026
  6. self-assigned this
    on Jun 9, 2026
  7. moved this to In Progress in Java Toolingon Jun 9, 2026
  8. added this to the 0.20.0 milestone on Jun 9, 2026
  9. added 2 commits that reference this issue on Jun 9, 2026
    ecf7654
    32e7dcf
  10. moved this from In Progress to Done in Java Toolingon Jun 9, 2026
  11. added a commit that references this issue on Jun 9, 2026
    1731550
  12. sampaio96 commented on Jun 9, 2026

    @sampaio96

    @sampaio96 you mean that LSPUsageSearcher should be fixed?

    Not just LSPUsageSearcher. I mean that LSPDocumentLinkAnnotator also needs to be fixed, as it has the same deadlock pattern.

    The original issue description correctly identifies the problem in LSPUsageSearcher. However, I recently experienced a complete IDE freeze, and my thread dumps show the exact same waitUntilDone() blocking a ReadAction inside LSPDocumentLinkAnnotator.

    Here is the relevant part of my stack trace showing the same behavior in the annotator:

    "JobScheduler FJ pool 2/9" prio=0 tid=0x0 nid=0x0 waiting on condition
        ...
    	at java.base@21.0.10/java.util.concurrent.CompletableFuture.get(Unknown Source)
    	at com.redhat.devtools.lsp4ij.internal.CompletableFutures.waitUntilDone(CompletableFutures.java:144)
    	at com.redhat.devtools.lsp4ij.internal.CompletableFutures.waitUntilDone(CompletableFutures.java:111)
    	at com.redhat.devtools.lsp4ij.features.documentLink.LSPDocumentLinkAnnotator.collectInformation(LSPDocumentLinkAnnotator.java:71)
    	at com.intellij.codeInsight.daemon.impl.ExternalToolPass.collectInformationWithProgress(ExternalToolPass.java:136)
        ...
    	at com.intellij.platform.locking.impl.NestedLocksThreadingSupport.tryRunReadAction(NestedLocksThreadingSupport.kt:901)
    	at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1237)

    It looks like any place in the codebase where waitUntilDone() is called while a Read Lock is held will need to be patched.

  13. angelozerr commented on Jun 9, 2026

    @angelozerr
    Contributor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions