From 855ad4ac1b68cdd174c9ea6aa64ff8bc7c576258 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Mon, 23 Nov 2026 18:35:01 +0900 Subject: [PATCH] =?UTF-8?q?fix(lock):=20in-process=20=EB=9D=BD=EC=9D=B4=20?= =?UTF-8?q?hashCode=EA=B0=80=20=EA=B0=99=EC=9D=80=20=EB=8B=A4=EB=A5=B8=20k?= =?UTF-8?q?ey=EB=A5=BC=20=EB=A7=89=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 단일 인스턴스 경로(multi-instance-enabled가 false이거나 없음)의 락 provider는 Spring Integration DefaultLockRegistry()다. ReentrantLock 256개를 미리 만들고 key.hashCode() & 255로 하나를 고르므로, 아래 8비트가 같은 다른 key("Aa"와 "BB")가 같은 락을 쓴다. 한 스레드가 "Aa"를 쥐면 다른 스레드의 "BB" 요청이 거짓 timeout으로 끝나고, 한 스레드가 두 key를 쥐면 보유가 한 락의 횟수로 합쳐져 하나를 풀어도 그 key가 풀리지 않는다. 포트 계약 시험의 「다른 key는 서로 막지 않는다」를 어긴다. InProcessLockRegistry를 더해 in-process provider가 쓰게 한다. key마다 ReentrantLock 하나를 두고, 그 key를 쥔 보유 수와 기다리는 수를 ConcurrentHashMap.compute 안에서만 세어 0이 되면 표에서 뺀다. unlock은 먼저 풀고 나서 세므로 쥔 채로 표에서 빠지지 않는다. 어댑터가 부르는 tryLock(long, TimeUnit)과 unlock()만 받고, 끝없이 기다리는 lock()· lockInterruptibly()와 쓰지 않는 tryLock()·newCondition()은 UnsupportedOperationException이다. 버린 안: DefaultLockRegistry(0xFFFF)는 확률만 줄이고 칸 수만큼 락을 미리 만든다. 문서에 「다른 key가 막을 수 있다」고 적으면 계약과 어긋난 채 남는다. 포트를 직접 구현하는 in-process 어댑터는 LockRegistryDistributedLock의 TTL 가드와 닫기 표시를 두 벌로 만든다. 포트 계약 시험 DistributedLockContract에 hashCode가 같은 다른 key 사례를 더해 fake와 PostgreSQL adapter가 함께 본다. in-process provider도 이 계약을 상속한다(InProcessDistributedLockTest.SharedPortContract). 락이 스레드에 묶여 있으므로 두 번째 인스턴스는 시험 도우미 LockPortOnItsOwnThread가 자기 스레드 하나에서 부르는 같은 provider다. 그래서 persistence-jpa의 application-core testFixtures 의존을 postgresqlIntegrationTestImplementation에서 testImplementation으로 옮긴다(postgresqlIntegrationTest는 testImplementation을 이어받는다. lockfile 변화 없음). InProcessLockRegistryTest는 10,000 key 뒤 표 크기, 8스레드가 같은 두 key를 다투는 경주(전체에 상한 하나), timeout· interrupt 뒤 남는 항목, 쥐지 않은 스레드의 unlock, 지원하지 않는 호출을 본다. 어댑터 단위 시험도 새 registry 위에서 돈다. 위험·한계: 같은 key의 재진입은 그대로다. 한 스레드가 쥔 다른 key는 key마다 따로 풀린다. 템플릿 main에는 이 포트로 락을 잡는 호출자가 없고, 파생 서비스는 거짓 timeout이 사라질 뿐 따라 고칠 코드가 없어 업그레이드 안내는 두지 않는다. unlock을 먼저 풀고 나서 세는 순서는 결정적 시험으로 보이지 못해 코드와 주석으로만 둔다. 경주 시험은 확률로 잡는다. 검증(desktop, 공유 잠금, --rerun --no-build-cache --no-daemon): - RED: base 93a417a5에 시험·build.gradle 네 파일만 얹은 트리 0c03a806에서 InProcessDistributedLockTest 6건 중 두 key 중 하나 풀기와 계약 사례 hashCode 같은 key 2건이 LockAcquisitionTimeoutException 으로 실패(rc=1). 같은 트리의 PostgreSQL lane은 10건 rc=0. - 고친 트리 5a9501a6(이 커밋과 경주 시험의 대기 두 줄만 다름): lock 패키지 단위 42건, fake 계약 5건, PostgreSQL lane 10건 rc=0. - 변이 7개(provider를 DefaultLockRegistry로 되돌림, 표에서 안 뺌, 실패한 tryLock에서 안 셈, interrupt 경로에서 안 셈, null 검사 뺌, 보유 검사 뺌, compute 대신 computeIfAbsent+users++)가 각각 겨냥한 시험만 실패시킨다(rc=1, 마지막은 3회 모두). - 경주 시험의 전체 상한: racer가 1초 간격으로 끝나는 탐침에서 racer마다 기다리던 판은 통과(8.1초), 한 번 정한 마감을 쓰는 이 커밋은 3초에서 TimeoutException으로 실패. Refs: REV-BE-0060 --- docs/testing/TESTING_STRATEGY.md | 2 +- .../outbound/persistence-jpa/README.md | 22 +- .../outbound/persistence-jpa/build.gradle | 4 +- .../DistributedLockPersistenceConfig.java | 11 +- .../lock/InProcessLockRegistry.java | 123 ++++++++++ .../lock/InProcessDistributedLockTest.java | 75 ++++++ .../lock/InProcessLockRegistryTest.java | 216 ++++++++++++++++++ .../lock/LockPortOnItsOwnThread.java | 76 ++++++ .../lock/LockRegistryDistributedLockTest.java | 9 +- src/application/core/README.md | 6 +- .../lock/testkit/DistributedLockContract.java | 31 ++- 11 files changed, 554 insertions(+), 21 deletions(-) create mode 100644 src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessLockRegistry.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessDistributedLockTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessLockRegistryTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockPortOnItsOwnThread.java diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index b28e2a03..837c6c80 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -220,7 +220,7 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌 | `CorrelationIdPort` | `observability.testkit.CorrelationIdContract` | `FixedCorrelationId` | `MdcCorrelationIdPortAdapterContractTest` — web (`test`) | | `CacheRegionPort` | `cache.testkit.CacheRegionContract` | `InMemoryCacheRegion` | `RedisCacheRegionContractTest`(`test`) · `LiveRedisCacheRegionContractTest`(`redisTopologyTest`) | | `DistributedLeasePort` | `lease.testkit.DistributedLeaseContract` | `InMemoryDistributedLease` | `RedisDistributedLeaseContractTest` · `LiveRedisDistributedLeaseContractTest` | -| `DistributedLockPort` | `lock.testkit.DistributedLockContract` | `InMemoryDistributedLock` | `PostgreSqlDistributedLockIntegrationTest` (`postgresqlDistributedLockIntegrationTest`) | +| `DistributedLockPort` | `lock.testkit.DistributedLockContract` | `InMemoryDistributedLock` | `InProcessDistributedLockTest`(단일 인스턴스 in-process provider, 두 번째 인스턴스는 다른 스레드) — persistence-jpa (`test`) · `PostgreSqlDistributedLockIntegrationTest` (`postgresqlDistributedLockIntegrationTest`) | | `DurableOperationStorePort` | `operation.testkit.DurableOperationStoreContract` | `InMemoryDurableOperationStore` | `JpaDurableOperationStoreContractTest` (`jpaPlatformContractTest`) | | `IntegrationEventEncoderPort` | `messaging.event.testkit.IntegrationEventEncoderContract` | `FakeIntegrationEventEncoder` | `JsonIntegrationEventEncoderContractTest` — support (`test`) | | `OutboxStorePort` (lease fencing) | `outbox.testkit.OutboxLeaseFencingContract` | `InMemoryOutboxStore` | `PostgreSqlOutboxConcurrentRelayIntegrationTest` | diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 890e8e2c..73ea3359 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -559,11 +559,29 @@ provider 선택(flag → bean → registry)의 정본은 설정 코드 `lock/Dis 실패해서, 얻은 스레드가 여전히 풀 수 있다. `InterruptedException` 은 interrupt flag 를 복원하고 `LockAcquisitionTimeoutException` 으로 변환한다. +### in-process registry (`InProcessLockRegistry`) +- 단일 인스턴스 경로(`multi-instance-enabled` 가 false·없음)의 registry 다. key 마다 `ReentrantLock` 하나를 두고, + 그 key 를 쥔 스레드도 기다리는 스레드도 없으면 표에서 뺀다. 그래서 다른 key 는 hashCode 가 같아도 서로 막지 + 않고(포트 계약 시험 `DistributedLockContract` 의 `differentKeysDoNotContend`· + `differentKeysWithTheSameHashCodeDoNotContend`), 한 번 쓰고 만 key 가 표에 쌓이지 않는다. +- 이 provider 도 그 계약 시험을 상속한다(`InProcessDistributedLockTest`). 락이 스레드에 묶여 있어 두 번째 + 인스턴스는 다른 스레드에서 부른 같은 provider 다. +- 같은 key 는 재진입한다. 같은 스레드가 다시 얻으면 바로 얻고, 핸들마다 한 번씩 닫아야 풀린다. 한 + 스레드가 쥔 다른 key 들은 key 마다 따로 풀린다. 하나를 닫으면 그 key 를 기다리던 다른 스레드가 바로 얻는다. +- 돌려주는 락은 어댑터가 부르는 `tryLock(long, TimeUnit)` 과 `unlock()` 만 받는다. `lock()`·`lockInterruptibly()` + 는 끝없이 기다리므로(D5) 나머지와 함께 `UnsupportedOperationException` 이다. 그 key 를 쥐지 않은 스레드의 + `unlock()` 은 `IllegalMonitorStateException` 이다. + +> 이력: 2026-11-23까지는 Spring Integration `DefaultLockRegistry()` 였다. `ReentrantLock` 256개를 미리 만들고 +> `key.hashCode() & 255` 로 하나를 골라, 아래 8비트가 같은 다른 key(예: `"Aa"` 와 `"BB"`)가 같은 락을 썼다. 아무도 +> 쥐지 않은 key 의 요청이 `LockAcquisitionTimeoutException` 으로 끝났고, 한 스레드가 두 key 를 쥐면 보유가 한 +> 락의 횟수로 합쳐졌다. 칸 수를 늘리는 `DefaultLockRegistry(int)` 는 확률만 줄여 쓰지 않았다. + ### TTL 주의 (SI 7.0) - `JdbcLockRegistry`: 기본 TTL 은 `JdbcLockRegistry(LockRepository, Duration)` 생성자로 설정하고, acquisition 별 TTL 은 `DistributedLock.tryLock(Duration waitTime, Duration ttl)` 로 전달한다. 크래시한 JVM 의 row 는 lock TTL 만료 후 다음 acquire 시도에서 회수된다. -- `DefaultLockRegistry`: TTL 은 advisory 이고 무의미하다 — JVM 크래시가 in-JVM 락을 프로세스와 +- `InProcessLockRegistry`: TTL 은 advisory 이고 무의미하다 — JVM 크래시가 in-JVM 락을 프로세스와 함께 자동으로 떨군다. ### SI-LOCK-C5 — lease 만료 후 release @@ -571,7 +589,7 @@ provider 선택(flag → bean → registry)의 정본은 설정 코드 `lock/Dis 의 경우, 내부 `JdbcLock.unlock()` 이 `ConcurrentModificationException` 을 던진다(row 가 이미 회수됨). 이 어댑터는 여기서 일부러 잡지 않는다 — metered `distributedLockProvider` 데코레이터 (이 모듈의 `DistributedLockPersistenceConfig`가 감싼 `MeteredDistributedLock`)가 SI-LOCK-C5 계약을 소유한다: 로그 + `lock.lease.expired` metric 후 `close()` 에서 -정상 return 해, 만료가 호출자의 보호작업 예외를 가리지 않게 한다. in-process `DefaultLockRegistry` +정상 return 해, 만료가 호출자의 보호작업 예외를 가리지 않게 한다. in-process `InProcessLockRegistry` 경로는 만료가 없어 그 `close()` 가 이 예외를 던질 수 없다. ### `DistributedLockPersistenceConfig` 와이어링 결정 diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index 69b8a16a..ea53aaff 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -132,7 +132,9 @@ dependencies { // The application-owned store contracts the notification adapters are held to, the same ones // the in-memory fakes pass (review 04-14). postgresqlIntegrationTestImplementation testFixtures(project(':application-notification')) - postgresqlIntegrationTestImplementation testFixtures(project(':application-core')) + // The application-core port contracts: the in-process lock provider passes DistributedLockContract + // in `test`, the PostgreSQL adapters in postgresqlIntegrationTest (which extends testImplementation). + testImplementation testFixtures(project(':application-core')) postgresqlIntegrationTestImplementation 'org.testcontainers:testcontainers-postgresql' postgresqlIntegrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' postgresqlIntegrationTestImplementation 'org.testcontainers:testcontainers-toxiproxy' diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java index c730b058..f4dbcf30 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java @@ -12,13 +12,12 @@ import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.integration.jdbc.lock.DefaultLockRepository; import org.springframework.integration.jdbc.lock.JdbcLockRegistry; -import org.springframework.integration.support.locks.DefaultLockRegistry; /** - * Spring wiring for the distributed-lock infrastructure: in-process {@link DefaultLockRegistry} by - * default, JDBC {@link JdbcLockRegistry} when {@code multi-instance-enabled=true}, wrapped in the - * {@link MeteredDistributedLock} metrics decorator as the primary {@code distributedLockProvider}. - * See README "lock" for the provider-selection and wiring rationale. + * Spring wiring for the distributed-lock infrastructure: in-process {@link InProcessLockRegistry} + * by default, JDBC {@link JdbcLockRegistry} when {@code multi-instance-enabled=true}, wrapped in + * the {@link MeteredDistributedLock} metrics decorator as the primary {@code + * distributedLockProvider}. See README "lock" for the provider-selection and wiring rationale. */ @Configuration(proxyBeanMethods = false) public class DistributedLockPersistenceConfig { @@ -55,7 +54,7 @@ public class DistributedLockPersistenceConfig { DistributedLockPort inProcessDistributedLock( LockSettings settings, ObjectProvider meterRegistry) { return new MeteredDistributedLock( - new LockRegistryDistributedLock(new DefaultLockRegistry(), settings.leaseTtl()), + new LockRegistryDistributedLock(new InProcessLockRegistry(), settings.leaseTtl()), meterRegistry); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessLockRegistry.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessLockRegistry.java new file mode 100644 index 00000000..d54bc13b --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessLockRegistry.java @@ -0,0 +1,123 @@ +package dev.caskeleton.adapter.outbound.persistence.lock; + +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import org.springframework.integration.support.locks.LockRegistry; + +/** + * The in-process {@link LockRegistry}: one {@link ReentrantLock} per key, kept only while a thread + * holds or waits for that key. Spring Integration's {@code DefaultLockRegistry} hashes keys onto + * 256 shared locks, so two different keys could block each other. See README "lock". + * + *

The returned lock supports only what {@link LockRegistryDistributedLock} calls: {@link + * Lock#tryLock(long, TimeUnit)} and {@link Lock#unlock()}. The rest throw {@link + * UnsupportedOperationException}: {@code lock()} and {@code lockInterruptibly()} wait without a + * bound (D5), and nothing here needs {@code tryLock()} or a {@link Condition}. + */ +final class InProcessLockRegistry implements LockRegistry { + + private final ConcurrentHashMap entries = new ConcurrentHashMap<>(); + + @Override + public Lock obtain(Object lockKey) { + return new KeyLock(Objects.requireNonNull(lockKey, "lockKey")); + } + + /** The number of keys some thread holds or waits for. */ + int size() { + return entries.size(); + } + + /** Counts this thread in on {@code key}'s entry, creating it if no one holds or waits for it. */ + private Entry pin(Object key) { + return entries.compute( + key, + (k, existing) -> { + Entry entry = existing == null ? new Entry() : existing; + entry.users++; + return entry; + }); + } + + /** Counts this thread out; the entry goes once no thread holds or waits for its key. */ + private void unpin(Object key) { + entries.computeIfPresent(key, (k, entry) -> --entry.users == 0 ? null : entry); + } + + private static final class Entry { + + private final ReentrantLock lock = new ReentrantLock(); + + /** Holds (one per reentrant hold) plus waits. Changed only inside a compute on this key. */ + private int users; + } + + private final class KeyLock implements Lock { + + private final Object key; + + private KeyLock(Object key) { + this.key = key; + } + + @Override + public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { + Entry entry = pin(key); + boolean acquired = false; + try { + acquired = entry.lock.tryLock(time, unit); + return acquired; + } finally { + if (!acquired) { + unpin(key); + } + } + } + + /** + * Releases one hold. While this thread holds the key, its entry cannot leave the table, so the + * entry found here is the one it locked. It unlocks before counting out, so an entry leaves the + * table only once no thread holds or waits for it. + * + * @throws IllegalMonitorStateException if this thread does not hold the key + */ + @Override + public void unlock() { + Entry entry = entries.get(key); + if (entry == null || !entry.lock.isHeldByCurrentThread()) { + throw new IllegalMonitorStateException("the current thread does not hold this lock"); + } + entry.lock.unlock(); + unpin(key); + } + + @Override + public void lock() { + throw unsupported(); + } + + @Override + public void lockInterruptibly() { + throw unsupported(); + } + + @Override + public boolean tryLock() { + throw unsupported(); + } + + @Override + public Condition newCondition() { + throw unsupported(); + } + + private static UnsupportedOperationException unsupported() { + return new UnsupportedOperationException( + "an in-process registry lock supports only tryLock(long, TimeUnit) and unlock()"); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessDistributedLockTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessDistributedLockTest.java new file mode 100644 index 00000000..a806d542 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessDistributedLockTest.java @@ -0,0 +1,75 @@ +package dev.caskeleton.adapter.outbound.persistence.lock; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.lock.DistributedLock; +import dev.caskeleton.application.lock.DistributedLockPort; +import dev.caskeleton.application.lock.testkit.DistributedLockContract; +import io.micrometer.core.instrument.MeterRegistry; +import java.time.Duration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; + +/** + * The provider the default single-instance wiring builds ({@code + * DistributedLockPersistenceConfig#inProcessDistributedLock}). Its locks are bound to a thread, so + * another instance is the same provider called from another thread: {@link LockPortOnItsOwnThread}. + */ +class InProcessDistributedLockTest { + + private static final Duration LEASE = Duration.ofSeconds(30); + private static final Duration SHORT_WAIT = Duration.ofMillis(100); + + private final DistributedLockPort provider = + new DistributedLockPersistenceConfig() + .inProcessDistributedLock( + new LockSettings(LEASE), + new DefaultListableBeanFactory().getBeanProvider(MeterRegistry.class)); + private final LockPortOnItsOwnThread otherThread = new LockPortOnItsOwnThread(provider); + + @AfterEach + void stopTheOtherThread() { + otherThread.close(); + } + + /** + * One thread holds two keys with the same hashCode. Releasing one must free that key, even though + * the thread still holds the other. + */ + @Test + void releasingOneOfTwoKeysHeldByOneThreadFreesThatKey() { + // given + assertThat("BB".hashCode()) + .as("given: the two keys share a hashCode") + .isEqualTo("Aa".hashCode()); + DistributedLock aa = provider.tryAcquire("Aa", SHORT_WAIT, LEASE); + DistributedLock bb = provider.tryAcquire("BB", SHORT_WAIT, LEASE); + aa.close(); + + // when + Throwable contender = + catchThrowable(() -> otherThread.tryAcquire("Aa", SHORT_WAIT, LEASE).close()); + + // then + bb.close(); + assertThat(contender).isNull(); + } + + /** The port contract: the test thread is one instance, another thread the other. */ + @Nested + class SharedPortContract extends DistributedLockContract { + + @Override + protected DistributedLockPort firstInstance() { + return provider; + } + + @Override + protected DistributedLockPort secondInstance() { + return otherThread; + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessLockRegistryTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessLockRegistryTest.java new file mode 100644 index 00000000..9812b404 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/InProcessLockRegistryTest.java @@ -0,0 +1,216 @@ +package dev.caskeleton.adapter.outbound.persistence.lock; + +import static org.assertj.core.api.Assertions.assertThat; +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.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.stream.Stream; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * {@link InProcessLockRegistry} keeps a key's lock only while a thread holds or waits for it. The + * table is read through {@code size()}; keys are taken through {@link LockRegistryDistributedLock}, + * as the single-instance wiring does. + */ +class InProcessLockRegistryTest { + + private static final Duration TTL = Duration.ofSeconds(30); + private static final Duration SHORT_WAIT = Duration.ofMillis(50); + // Bounds the wait for the other thread: far above SHORT_WAIT, so only a hang reaches it. + private static final Duration OTHER_THREAD_WAIT = Duration.ofSeconds(5); + // An acquire behind the other racing threads; far above their short holds. + private static final Duration CONTENDED_WAIT = Duration.ofSeconds(5); + // Bounds the whole race, so a lost or stuck thread fails the test instead of hanging it. + private static final Duration RACE_WAIT = Duration.ofSeconds(60); + + private final InProcessLockRegistry registry = new InProcessLockRegistry(); + private final LockRegistryDistributedLock sut = new LockRegistryDistributedLock(registry, TTL); + + @Test + void acquiringAndReleasingTenThousandKeysDoesNotGrowTheTable() { + // given + DistributedLock held = sut.tryAcquire("held", SHORT_WAIT, TTL); + + // when + for (int i = 0; i < 10_000; i++) { + sut.tryAcquire("key-" + i, SHORT_WAIT, TTL).close(); + } + + // then + int size = registry.size(); + held.close(); + assertThat(size).as("only the key still held").isOne(); + } + + /** + * Threads take two keys with the same hashCode over and over, all at once, so they count in and + * out of one entry together. A count that lost an update would drop an entry still in use, and a + * second lock for the same key would let two threads hold it at once. + */ + @Test + void threadsRacingForTheSameKeysHoldEachOneAtATimeAndLeaveNoEntryBehind() throws Exception { + // given + int threads = 8; + int rounds = 2_000; + Map holding = + Map.of("Aa", new AtomicInteger(), "BB", new AtomicInteger()); + AtomicInteger mostHoldingOneKey = new AtomicInteger(); + CountDownLatch start = new CountDownLatch(1); + ExecutorService pool = Executors.newFixedThreadPool(threads); + List> racers = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + racers.add( + pool.submit( + () -> { + assertThat(start.await(RACE_WAIT.toMillis(), TimeUnit.MILLISECONDS)) + .as("the race started") + .isTrue(); + for (int i = 0; i < rounds; i++) { + String key = i % 2 == 0 ? "Aa" : "BB"; + DistributedLock held = sut.tryAcquire(key, CONTENDED_WAIT, TTL); + try { + mostHoldingOneKey.accumulateAndGet( + holding.get(key).incrementAndGet(), Math::max); + holding.get(key).decrementAndGet(); + } finally { + held.close(); + } + } + return null; + })); + } + + // when + try { + start.countDown(); + long deadline = System.nanoTime() + RACE_WAIT.toNanos(); + for (Future racer : racers) { + racer.get(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); + } + } finally { + pool.shutdownNow(); + } + + // then + assertThat(List.of(mostHoldingOneKey.get(), registry.size())) + .as("most threads holding one key at once, entries left") + .containsExactly(1, 0); + } + + @Test + void anAcquireThatTimesOutLeavesNoEntryBehind() throws Exception { + // given + DistributedLock held = sut.tryAcquire("key", SHORT_WAIT, TTL); + assertThat(onAnotherThread(() -> catchThrowable(() -> sut.tryAcquire("key", SHORT_WAIT, TTL)))) + .as("given: another thread's acquire times out") + .isInstanceOf(LockAcquisitionTimeoutException.class); + held.close(); + + // when + int size = registry.size(); + + // then + assertThat(size).isZero(); + } + + @Test + void anInterruptedAcquireLeavesNoEntryBehind() throws Exception { + // given + assertThat( + onAnotherThread( + () -> { + Thread.currentThread().interrupt(); + return catchThrowable(() -> sut.tryAcquire("key", SHORT_WAIT, TTL)); + })) + .as("given: an acquire on an interrupted thread fails") + .isInstanceOf(LockAcquisitionTimeoutException.class); + + // when + int size = registry.size(); + + // then + assertThat(size).isZero(); + } + + @Test + void releasingAKeyNoThreadHoldsFails() { + // when + Throwable thrown = catchThrowable(() -> registry.obtain("key").unlock()); + + // then + assertThat(thrown) + .isInstanceOf(IllegalMonitorStateException.class) + .hasMessage("the current thread does not hold this lock"); + } + + @Test + void releasingAKeyAnotherThreadHoldsFails() throws Exception { + // given + DistributedLock held = sut.tryAcquire("key", SHORT_WAIT, TTL); + + // when + Throwable thrown = onAnotherThread(() -> catchThrowable(() -> registry.obtain("key").unlock())); + + // then + held.close(); + assertThat(thrown) + .isInstanceOf(IllegalMonitorStateException.class) + .hasMessage("the current thread does not hold this lock"); + } + + @ParameterizedTest + @MethodSource("unsupportedCalls") + void lockCallsOtherThanTheBoundedTryLockAndUnlockAreUnsupported(LockCall call) { + // given + Lock lock = registry.obtain("key"); + + // when + Throwable thrown = catchThrowable(() -> call.on(lock)); + + // then + assertThat(thrown) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage( + "an in-process registry lock supports only tryLock(long, TimeUnit) and unlock()"); + } + + static Stream> unsupportedCalls() { + return Stream.of( + Named.of("lock()", Lock::lock), + Named.of("lockInterruptibly()", Lock::lockInterruptibly), + Named.of("tryLock()", Lock::tryLock), + Named.of("newCondition()", Lock::newCondition)); + } + + /** One call on a {@link Lock}. */ + @FunctionalInterface + interface LockCall { + void on(Lock lock) throws Exception; + } + + /** 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); + Thread contender = new Thread(task, "lock-contender"); + contender.setDaemon(true); + contender.start(); + return task.get(OTHER_THREAD_WAIT.toMillis(), TimeUnit.MILLISECONDS); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockPortOnItsOwnThread.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockPortOnItsOwnThread.java new file mode 100644 index 00000000..be65fb62 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockPortOnItsOwnThread.java @@ -0,0 +1,76 @@ +package dev.caskeleton.adapter.outbound.persistence.lock; + +import dev.caskeleton.application.lock.DistributedLock; +import dev.caskeleton.application.lock.DistributedLockPort; +import java.time.Duration; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * A {@link DistributedLockPort} whose every call, handle closes included, runs on one thread of its + * own. A thread-bound lock sees that thread as another instance, so a test can contend with the + * test thread through it. Each call waits at most {@link #CALL_BOUND}; a failure on that thread is + * thrown here as it was thrown there. + */ +final class LockPortOnItsOwnThread implements DistributedLockPort, AutoCloseable { + + // Far above any wait a test gives the port, so only a hang reaches it. + private static final Duration CALL_BOUND = Duration.ofSeconds(5); + + private final DistributedLockPort port; + private final ExecutorService thread = + Executors.newSingleThreadExecutor( + task -> { + Thread own = new Thread(task, "lock-port-own-thread"); + own.setDaemon(true); + return own; + }); + + LockPortOnItsOwnThread(DistributedLockPort port) { + this.port = port; + } + + @Override + public DistributedLock tryAcquire(String key, Duration waitTime, Duration leaseTtl) { + DistributedLock handle = onItsThread(() -> port.tryAcquire(key, waitTime, leaseTtl)); + return () -> + onItsThread( + () -> { + handle.close(); + return null; + }); + } + + /** Stops the thread. A lock it still holds stays held; each test builds its own provider. */ + @Override + public void close() { + thread.shutdownNow(); + } + + private T onItsThread(Callable call) { + Future result = thread.submit(call); + try { + return result.get(CALL_BOUND.toMillis(), TimeUnit.MILLISECONDS); + } catch (ExecutionException e) { + if (e.getCause() instanceof RuntimeException failure) { + throw failure; + } + if (e.getCause() instanceof Error error) { + throw error; + } + throw new IllegalStateException(e.getCause()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while waiting for the port's own thread", e); + } catch (TimeoutException e) { + result.cancel(true); + throw new IllegalStateException( + "the port's own thread did not finish within " + CALL_BOUND, e); + } + } +} 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 4ee02617..6558e011 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 @@ -14,12 +14,11 @@ 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). The failed-release tests use a registry - * whose lock fails on release instead. + * Pure unit tests for {@link LockRegistryDistributedLock} over the {@link InProcessLockRegistry} + * the single-instance wiring uses (no database, no Spring context). The failed-release tests use a + * registry whose lock fails on release instead. * *

Determinism strategy

* @@ -39,7 +38,7 @@ class LockRegistryDistributedLockTest { private static final Duration OTHER_THREAD_WAIT = Duration.ofSeconds(5); private LockRegistryDistributedLock adapter() { - return new LockRegistryDistributedLock(new DefaultLockRegistry(), CONFIGURED_TTL); + return new LockRegistryDistributedLock(new InProcessLockRegistry(), CONFIGURED_TTL); } // ------------------------------------------------------------------ diff --git a/src/application/core/README.md b/src/application/core/README.md index c8bfc15d..adccd40a 100644 --- a/src/application/core/README.md +++ b/src/application/core/README.md @@ -543,14 +543,14 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt - 분산 락 획득 outbound 포트. - **왜 이 포트가 있나(D2)**: 유스케이스는 락 클라이언트·Spring `LockRegistry`·advisory-lock SQL 을 직접 import 하면 안 된다. 이 포트가 application-core 안에서 협조적 상호배제를 위해 허용된 - 유일한 의존이다. adapter 구현(`JdbcLockRegistry` 멀티 인스턴스, `DefaultLockRegistry` 단일 - 인스턴스)은 `adapter-persistence` 에 있고 컴파일 타임엔 application 계층에 안 보인다. + 유일한 의존이다. adapter 구현(`JdbcLockRegistry` 멀티 인스턴스, `InProcessLockRegistry` 단일 + 인스턴스, key 마다 락 하나)은 `:adapter:outbound:persistence-jpa` 에 있고 컴파일 타임엔 application 계층에 안 보인다. - **try-lock + 유한 waitTime + 필수 leaseTtl(D5)**: `tryAcquire` 는 try-lock 이다 — 최대 `waitTime` 만 블로킹하고 held 핸들을 반환하거나 `LockAcquisitionTimeoutException` 을 던진다. 무한 블로킹은 금지(항상 유한 `waitTime` 공급). `leaseTtl` 은 JVM 이 `close()` 전에 죽어도 adapter 가 락을 유지하는 최대 시간으로, 죽은 보유자가 시스템을 무한 데드락 시키는 것을 막는다. `JdbcLockRegistry` 는 registry 기본 TTL 과 호출별 lock TTL 을 강제하고, in-process - `DefaultLockRegistry` 는 advisory(강제 없음)다. + `InProcessLockRegistry` 는 advisory(강제 없음)다. - **트랜잭션 커밋 순서 불변식(D4)**: 반환된 핸들은 보호 작업의 DB 트랜잭션이 **커밋된 후에만** 해제해야 한다. 트랜잭션 안(커밋 전)에서 해제하면 lost-update 경합이 생긴다 — 두 번째 스레드가 락을 얻어, 첫 트랜잭션의 쓰기가 DB 에 보이기 전에 자신의 read-modify-write 를 시작한다. 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 5c699f30..6958a796 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 @@ -11,12 +11,13 @@ import java.util.UUID; import org.junit.jupiter.api.Test; /** - * What every {@link DistributedLockPort} promises, run by the fake's test and the JDBC adapter's - * PostgreSQL test alike. + * What every {@link DistributedLockPort} promises, run by the fake's test, the in-process + * provider's test and the JDBC adapter's PostgreSQL test alike. * *

Contention is between two instances — two ports over one lock store — because that is * what the lock exists for. Two acquires through one instance from one thread prove nothing: a - * thread-bound lock lets them both through. + * thread-bound lock lets them both through. For the in-process provider, whose locks are bound to a + * thread, the second instance is the same provider called from another thread. */ public abstract class DistributedLockContract { @@ -90,6 +91,30 @@ public abstract class DistributedLockContract { assertThat(thrown).isNull(); } + /** + * Keys with the same {@link String#hashCode()} are still different keys. A store that hashes keys + * onto a fixed set of locks makes them block each other. + */ + @Test + void differentKeysWithTheSameHashCodeDoNotContend() { + // given + String prefix = uniqueKey() + "-"; + String heldKey = prefix + "Aa"; + String otherKey = prefix + "BB"; + assertThat(otherKey.hashCode()) + .as("given: the two keys share a hashCode") + .isEqualTo(heldKey.hashCode()); + DistributedLock held = firstInstance().tryAcquire(heldKey, SHORT_WAIT, LEASE); + + // when + Throwable thrown = + catchThrowable(() -> secondInstance().tryAcquire(otherKey, SHORT_WAIT, LEASE).close()); + + // then + held.close(); + assertThat(thrown).isNull(); + } + private static String uniqueKey() { return "contract-" + UUID.randomUUID(); } -- 2.54.0