From 9771ed531d560ee9bf5edd63392d25589786fdd9 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 09:12:32 +0900 Subject: [PATCH] =?UTF-8?q?fix(lock):=20=EB=9D=BD=20=ED=95=B8=EB=93=A4?= =?UTF-8?q?=EC=9D=84=20=EB=8B=A4=EC=8B=9C=20=EB=8B=AB=EC=95=84=EB=8F=84=20?= =?UTF-8?q?=EC=98=88=EC=99=B8=20=EC=97=86=EC=9D=B4=20=EB=8B=A4=EB=A5=B8=20?= =?UTF-8?q?=EB=B3=B4=EC=9C=A0=EB=A5=BC=20=ED=92=80=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JDBC·in-process 락 adapter의 핸들은 `l::unlock`이라 닫을 때마다 다시 unlock한다. 보유가 하나면 두 번째 close가 IllegalMonitorStateException을 던진다. 같은 스레드가 같은 key를 재진입으로 두 번 쥐었으면 한 핸들의 두 번째 close가 예외 없이 다른 핸들의 보유를 풀어, 그 핸들이 열린 채 다른 스레드가 락을 얻는다. 포트는 close가 idempotent하다고 약속하고 fake는 그렇게 돈다. 공유 계약에 다시 닫는 시험이 없어 둘이 갈라진 것을 못 봤다. 핸들마다 닫힘 표시를 둔다. 락을 얻은 스레드의 첫 close가 unlock 전에 표시하고, 표시가 있으면 close는 바로 돌아온다. unlock이 실패해도 다음 close는 아무것도 하지 않는다. 다른 스레드의 close는 표시를 남기지 않고 registry 락처럼 실패해서, 얻은 스레드가 여전히 풀 수 있다. 버린 안: compareAndSet 뒤 unlock은 잘못된 스레드의 close가 표시를 먼저 남겨 주인이 못 푼다. IllegalMonitorStateException을 삼키면 재진입에서 남의 보유를 푸는 것이 그대로다. 계약에서 idempotent를 빼면 fake와 문서의 약속이 약해진다. 위험·한계: registry 락이 스레드에 묶인다고 가정한다(JdbcLockRegistry와 DefaultLockRegistry 모두 ReentrantLock 기반). 스레드에 묶이지 않는 registry를 쓰면 다른 스레드의 close 뒤 주인의 close가 한 번 더 unlock한다. lease 만료의 ConcurrentModificationException 처리와 그 밖 예외의 전파는 그대로다. 검증: 고치기 전 RED, 변이 셋, 게이트 결과는 PR 본문에 적는다. Refs: REV-BE-0057 --- .../outbound/persistence-jpa/README.md | 8 +- .../lock/LockRegistryDistributedLock.java | 24 ++- .../lock/LockRegistryDistributedLockTest.java | 137 +++++++++++++++++- .../lock/testkit/DistributedLockContract.java | 14 ++ 4 files changed, 179 insertions(+), 4 deletions(-) diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index df248226..890e8e2c 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -552,7 +552,11 @@ provider 선택(flag → bean → registry)의 정본은 설정 코드 `lock/Dis 긴 lease 를 약속하는 건 false contract 다. shipped 와이어링에선 `leaseTtl == configuredTtl` (둘 다 `LockSettings.leaseTtl()` 바인딩)이라 이 가드는 mis-wired 호출자/테스트에서만 fail-fast 로 발동한다. -- 반환 핸들은 `lock::unlock` 람다(SAM 인터페이스 충족). `InterruptedException` 은 interrupt flag +- 반환 핸들의 `close()` 는 닫힘 표시가 없을 때만 `lock.unlock()` 을 부른다. 락을 얻은 스레드의 + close 는 unlock 전에 표시를 남기므로, unlock 이 실패해도 다음 `close()` 는 아무것도 하지 않는다(포트의 + idempotent 약속). registry 락은 스레드에 묶이고 재진입하므로, 같은 핸들을 다시 unlock 하면 같은 + 스레드가 쥔 다른 핸들의 보유가 풀린다. 다른 스레드의 `close()` 는 표시를 남기지 않고 registry 락처럼 + 실패해서, 얻은 스레드가 여전히 풀 수 있다. `InterruptedException` 은 interrupt flag 를 복원하고 `LockAcquisitionTimeoutException` 으로 변환한다. ### TTL 주의 (SI 7.0) @@ -563,7 +567,7 @@ provider 선택(flag → bean → registry)의 정본은 설정 코드 `lock/Dis 함께 자동으로 떨군다. ### SI-LOCK-C5 — lease 만료 후 release -반환 핸들은 `lock::unlock` 이다. lease TTL 이 `close()` 전에 만료된 `JdbcLockRegistry` +락을 얻은 스레드의 첫 `close()` 가 `lock.unlock()` 을 부른다. lease TTL 이 `close()` 전에 만료된 `JdbcLockRegistry` 의 경우, 내부 `JdbcLock.unlock()` 이 `ConcurrentModificationException` 을 던진다(row 가 이미 회수됨). 이 어댑터는 여기서 일부러 잡지 않는다 — metered `distributedLockProvider` 데코레이터 (이 모듈의 `DistributedLockPersistenceConfig`가 감싼 `MeteredDistributedLock`)가 SI-LOCK-C5 계약을 소유한다: 로그 + `lock.lease.expired` metric 후 `close()` 에서 diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java index ce984c7a..fdf86fb4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java @@ -4,6 +4,7 @@ import dev.caskeleton.application.lock.DistributedLockPort; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; import java.time.Duration; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import org.springframework.integration.support.locks.DistributedLock; import org.springframework.integration.support.locks.LockRegistry; @@ -52,6 +53,27 @@ public class LockRegistryDistributedLock implements DistributedLockPort { if (!acquired) { throw new LockAcquisitionTimeoutException(key, waitTime); } - return l::unlock; + return releasedOnceByOwner(l); + } + + /** + * The handle's {@code close()} must be idempotent (port contract), and registry locks are + * thread-bound and reentrant: unlocking again would release another handle's hold. The first + * close on the acquiring thread marks the handle before it unlocks, so a later close does nothing + * even when that unlock failed. A close on another thread leaves no mark and fails as the + * registry lock does, so the acquiring thread can still release. + */ + private static dev.caskeleton.application.lock.DistributedLock releasedOnceByOwner(Lock lock) { + Thread owner = Thread.currentThread(); + AtomicBoolean closed = new AtomicBoolean(); + return () -> { + if (closed.get()) { + return; + } + if (Thread.currentThread() == owner) { + closed.set(true); + } + lock.unlock(); + }; } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java index 93c52c49..4ee02617 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java @@ -2,18 +2,24 @@ package dev.caskeleton.adapter.outbound.persistence.lock; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.lock.DistributedLock; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; import java.time.Duration; +import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; import org.junit.jupiter.api.Test; import org.springframework.integration.support.locks.DefaultLockRegistry; /** * Pure unit tests for {@link LockRegistryDistributedLock} over an in-process {@link - * DefaultLockRegistry} (no database, no Spring context). + * DefaultLockRegistry} (no database, no Spring context). The failed-release tests use a registry + * whose lock fails on release instead. * *

Determinism strategy

* @@ -21,11 +27,16 @@ import org.springframework.integration.support.locks.DefaultLockRegistry; * The background thread acquires the lock and signals readiness before the main thread makes a * contending attempt. The background thread releases the lock only after the main thread's * assertion completes. This avoids timing-based sleeps. + * + *

Tests whose handles must stay on the test thread contend from another thread instead, through + * {@code onAnotherThread}, which waits at most {@code OTHER_THREAD_WAIT}. */ class LockRegistryDistributedLockTest { private static final Duration CONFIGURED_TTL = Duration.ofSeconds(30); private static final Duration SHORT_WAIT = Duration.ofMillis(50); + // Bounds the wait for work on another thread: far above SHORT_WAIT, so only a hang reaches it. + private static final Duration OTHER_THREAD_WAIT = Duration.ofSeconds(5); private LockRegistryDistributedLock adapter() { return new LockRegistryDistributedLock(new DefaultLockRegistry(), CONFIGURED_TTL); @@ -146,4 +157,128 @@ class LockRegistryDistributedLockTest { assertThat(second).isNotNull(); second.close(); } + + // ------------------------------------------------------------------ + // close() is idempotent and releases only its own hold + // ------------------------------------------------------------------ + + @Test + void closingTheOnlyHandleTwiceDoesNotThrow() { + // given + DistributedLock held = adapter().tryAcquire("key-6", SHORT_WAIT, CONFIGURED_TTL); + held.close(); + + // when + Throwable thrown = catchThrowable(held::close); + + // then + assertThat(thrown).isNull(); + } + + /** + * One thread holds a key twice through reentrant handles a and b. Closing a again must not drop + * b's hold, so another thread still times out while b is open. + */ + @Test + void closingOneOfTwoReentrantHandlesTwiceKeepsTheOtherHold() throws Exception { + // given + LockRegistryDistributedLock sut = adapter(); + String key = "key-7"; + DistributedLock a = sut.tryAcquire(key, SHORT_WAIT, CONFIGURED_TTL); + DistributedLock b = sut.tryAcquire(key, SHORT_WAIT, CONFIGURED_TTL); + a.close(); + a.close(); + + // when + Throwable contender = onAnotherThread(() -> acquireAndRelease(sut, key)); + + // then + assertThat(contender) + .as("another thread's acquire while handle b is still open") + .isInstanceOfSatisfying( + LockAcquisitionTimeoutException.class, e -> assertThat(e.key()).isEqualTo(key)); + b.close(); + } + + @Test + void aFailedReleasePropagatesTheRegistryException() { + // given + ReleaseFailingLock lock = new ReleaseFailingLock(); + DistributedLock held = + new LockRegistryDistributedLock(key -> lock, CONFIGURED_TTL) + .tryAcquire("key-8", SHORT_WAIT, CONFIGURED_TTL); + + // when + Throwable thrown = catchThrowable(held::close); + + // then + assertThat(thrown).isSameAs(lock.failure); + } + + @Test + void closingAgainAfterAFailedReleaseDoesNotThrow() { + // given + ReleaseFailingLock lock = new ReleaseFailingLock(); + DistributedLock held = + new LockRegistryDistributedLock(key -> lock, CONFIGURED_TTL) + .tryAcquire("key-9", SHORT_WAIT, CONFIGURED_TTL); + assertThat(catchThrowable(held::close)) + .as("given: the first close fails") + .isSameAs(lock.failure); + + // when + Throwable thrown = catchThrowable(held::close); + + // then + assertThat(thrown).isNull(); + } + + /** + * A close from a thread that does not hold the lock fails and must not use up the handle: the + * acquiring thread's close afterwards still releases the key. + */ + @Test + void theOwnerStillReleasesAfterAnotherThreadsCloseFailed() throws Exception { + // given + LockRegistryDistributedLock sut = adapter(); + String key = "key-10"; + DistributedLock held = sut.tryAcquire(key, SHORT_WAIT, CONFIGURED_TTL); + assertThat(onAnotherThread(() -> catchThrowable(held::close))) + .as("given: a close from another thread fails") + .isInstanceOf(IllegalMonitorStateException.class); + held.close(); + + // when + Throwable contender = onAnotherThread(() -> acquireAndRelease(sut, key)); + + // then + assertThat(contender).as("another thread's acquire after the owner's close").isNull(); + } + + private static Throwable acquireAndRelease(LockRegistryDistributedLock sut, String key) { + return catchThrowable(() -> sut.tryAcquire(key, SHORT_WAIT, CONFIGURED_TTL).close()); + } + + /** Runs {@code attempt} on a new thread, which the lock sees as another owner, within a bound. */ + private static Throwable onAnotherThread(Callable attempt) throws Exception { + FutureTask task = new FutureTask<>(attempt); + new Thread(task, "lock-contender").start(); + return task.get(OTHER_THREAD_WAIT.toMillis(), TimeUnit.MILLISECONDS); + } + + /** + * A registry lock whose release frees the local hold and then fails, as {@code JdbcLock.unlock()} + * does when deleting the lock row fails. + */ + @SuppressWarnings("serial") + private static final class ReleaseFailingLock extends ReentrantLock { + + private final RuntimeException failure = new IllegalStateException("lock row delete failed"); + + @Override + public void unlock() { + super.unlock(); + throw failure; + } + } } diff --git a/src/application/core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java b/src/application/core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java index d2b5c9e7..5c699f30 100644 --- a/src/application/core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java +++ b/src/application/core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java @@ -62,6 +62,20 @@ public abstract class DistributedLockContract { assertThat(thrown).isNull(); } + /** {@link DistributedLock#close()} is idempotent: a handle closed again must not throw. */ + @Test + void closingAReleasedHandleAgainDoesNotThrow() { + // given + DistributedLock held = firstInstance().tryAcquire(uniqueKey(), SHORT_WAIT, LEASE); + held.close(); + + // when + Throwable thrown = catchThrowable(held::close); + + // then + assertThat(thrown).isNull(); + } + @Test void differentKeysDoNotContend() { // given -- 2.54.0