fix(lock): in-process 락이 hashCode가 같은 다른 key를 막지 않는다 #107

Merged
donghyeon.kang merged 2 commits from fix/in-process-lock-per-key into main 2026-11-23 16:20:11 +00:00
11 changed files with 554 additions and 21 deletions
+1 -1
View File
@@ -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` |
+20 -2
View File
@@ -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` 와이어링 결정
@@ -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'
@@ -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> meterRegistry) {
return new MeteredDistributedLock(
new LockRegistryDistributedLock(new DefaultLockRegistry(), settings.leaseTtl()),
new LockRegistryDistributedLock(new InProcessLockRegistry(), settings.leaseTtl()),
meterRegistry);
}
@@ -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".
*
* <p>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<Lock> {
private final ConcurrentHashMap<Object, Entry> 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()");
}
}
}
@@ -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;
}
}
}
@@ -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<String, AtomicInteger> holding =
Map.of("Aa", new AtomicInteger(), "BB", new AtomicInteger());
AtomicInteger mostHoldingOneKey = new AtomicInteger();
CountDownLatch start = new CountDownLatch(1);
ExecutorService pool = Executors.newFixedThreadPool(threads);
List<Future<?>> 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<Named<LockCall>> 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<Throwable> attempt) throws Exception {
FutureTask<Throwable> 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);
}
}
@@ -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> T onItsThread(Callable<T> call) {
Future<T> 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);
}
}
}
@@ -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.
*
* <h2>Determinism strategy</h2>
*
@@ -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);
}
// ------------------------------------------------------------------
+3 -3
View File
@@ -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 를 시작한다.
@@ -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.
*
* <p>Contention is between two <em>instances</em> — 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();
}