Skip to content

fix(Lazy): release lock if supplier throws#66

Merged
nixel2007 merged 1 commit into
1c-syntax:masterfrom
sfaqer:fix/lazy-lock-leak
Jun 2, 2026
Merged

fix(Lazy): release lock if supplier throws#66
nixel2007 merged 1 commit into
1c-syntax:masterfrom
sfaqer:fix/lazy-lock-leak

Conversation

@sfaqer
Copy link
Copy Markdown
Member

@sfaqer sfaqer commented Jun 2, 2026

Summary

  • Lazy.getOrCompute(Supplier) обёрнут в try/finally: до фикса lock.unlock() стоял после maybeCompute(supplier) без guard, и любое RuntimeException из supplier'а оставляло lock захваченным до смерти потока.
  • Когда Lazy шарит внешний ReentrantLock с другими операциями (например DocumentContext.acquireLocks/rebuild/clearSecondaryData в bsl-language-server, где computeLock/diagnosticsLock переиспользуются), все последующие попытки взять lock зависали навсегда. Поток-владелец возвращался в pool idle и держал lock пожизненно.

Проявление

Стек у нас в проде показывал:

```
"doc-...ManagerModule.bsl-executor" waiting on condition

  • parking to wait for <0x...> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    at DocumentContext.acquireLocks(DocumentContext.java:387)
    at DocumentContext.rebuild(...)
    ```

Lock-owner — text-document-service-... в SynchronousQueue.take() (т.е. idle worker в пуле). RC: предыдущий task взял lock через Lazy.getOrCompute, supplier бросил RuntimeException, unlock() пропущен.

Test plan

  • LazyTest.supplierExceptionReleasesLock — после IllegalStateException из supplier'а lock.isLocked() == false, getHoldCount() == 0.
  • LazyTest.supplierExceptionReleasesSharedLockMultipleAttempts — два неудачных attempt'а подряд + успешный третий, lock корректно отпускается на каждом проходе.
  • Прочие тесты (getOrComputeReturnsValue/getOrComputeCachesValue/clearAllowsRecompute/getReturnsNullBeforeCompute) — поведение без изменений.

🤖 Generated with Claude Code

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 2, 2026

Review Change Stack

Warning

Review limit reached

@sfaqer, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 50 minutes and 2 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 03de0679-01bf-4c1e-a293-8bdd6729c634

📥 Commits

Reviewing files that changed from the base of the PR and between 37dd448 and 8e7c8c3.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/utils/Lazy.java
  • src/test/java/com/github/_1c_syntax/utils/LazyTest.java

Walkthrough

Pull Request модифицирует класс Lazy<T> для гарантированного освобождения ReentrantLock при исключениях во время вычисления значения через try/finally конструкцию. Добавлены комплексные тесты JUnit 5, валидирующие поведение кэширования, освобождение блокировки при ошибках и состояние кэша.

Changes

Гарантированное освобождение блокировки в Lazy

Layer / File(s) Summary
Исправление освобождения блокировки в getOrCompute()
src/main/java/com/github/_1c_syntax/utils/Lazy.java
Метод getOrCompute(Supplier<T>) обёрнут в try/finally блок для гарантированного вызова lock.unlock() при любых исключениях во время вычисления через maybeCompute().
Тестовое покрытие поведения Lazy
src/test/java/com/github/_1c_syntax/utils/LazyTest.java
Набор JUnit 5 тестов проверяет: корректность возврата и кэширования значений, гарантированное освобождение блокировки при RuntimeException из supplier'а (включая повторные попытки вычисления), сброс кэша через clear() с повторным вычислением, и поведение get() до и после первого вычисления.

Sequence Diagram(s)

sequenceDiagram
  participant Test as LazyTest
  participant Lazy as LazyT
  participant Lock as ReentrantLock
  Test->>Lazy: getOrCompute(supplier_success)
  Lazy->>Lock: lock()
  Lazy->>Lazy: maybeCompute(supplier)
  Lazy->>Lock: unlock() in finally
  Lazy-->>Test: value
  Test->>Lazy: getOrCompute(supplier_exception)
  Lazy->>Lock: lock()
  Lazy->>Lazy: maybeCompute(supplier) throws
  Lazy->>Lock: unlock() in finally
  Lazy-->>Test: exception released lock
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

Блокировка в finally живёт,
Исключенья больше не страшат,
Тесты проверят — всё пройдёт,
Кэш и свобода вновь блистят! 🔒✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Название точно описывает основное изменение: исправление утечки блокировки в методе getOrCompute путём обёртывания кода в try/finally.
Description check ✅ Passed Описание подробно объясняет проблему (утечка блокировки при исключении), её проявление в production и план тестирования, полностью соответствует changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sfaqer sfaqer force-pushed the fix/lazy-lock-leak branch from 37dd448 to 8e7c8c3 Compare June 2, 2026 07:06
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Jun 2, 2026

@nixel2007 nixel2007 merged commit 781d4d1 into 1c-syntax:master Jun 2, 2026
8 of 9 checks passed
@sentry
Copy link
Copy Markdown

sentry Bot commented Jun 3, 2026

Issues attributed to commits in this pull request

This pull request was merged and Sentry observed the following issues:

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.

2 participants