Skip to content

When the business thread is interrupted, watchdog renew listener keeps renewing lock #4368

Closed

Description

@Coean

Expected behavior
when tryLock is interrupted, watchdog renew listener is cancelled too

Actual behavior
when the thread is interrupted, watchdog keeps renewing lock, but i think it should not be renewed.

Someone once reported this issue in Issue-2714

and then another PR announced that it had solved the issue, but I don't think it had.
#3826

We can see the KEY LOGIC in the PR above, which detects whether watch dog's thread is interrupted, not whether our business thread is interrupted.

if (Thread.currentThread().isInterrupted()) {

Steps to reproduce or test case

 public void testLockRenewedAfterInterruptedTryLock() throws InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        RLock lock = redisson.getLock("myLock");

        Thread thread = new Thread(() -> {
            if (!lock.tryLock()) {
                return;
            }
            countDownLatch.countDown();
        });
        thread.start();
        countDownLatch.await();
        thread.interrupt();

        TimeUnit.SECONDS.sleep(45);
        lock.isLocked() // **Expected return false but it will be return true**
    }

Redis version
Redis 5.0.10

Redisson version
3.17.3

Activity

  1. mrniko commented on Jun 15, 2022

    @mrniko
    Member

    Reason of this issue explained here #2714 (comment)

    #3826 related to a different issue.

  2. Coean commented on Jun 15, 2022

    @Coean
    Author

    Reason of this issue explained here #2714 (comment)

    #3826 related to a different issue.

    I know that the watchdog works in Redisson instance scope not in thread, But if you look at the code i post, this is an existing problem, should we fix it?

    in this case, it will happen lock leak.

    Should we check the business thread status in watchdog? If the thread has been interrupted, no longer renew the lock.

  3. mrniko commented on Jun 16, 2022

    @mrniko
    Member

    I agree that Thread.currentThread().isInterrupted() check in scheduleExpirationRenewal() is useless.

  4. Coean commented on Jun 16, 2022

    @Coean
    Author

    I agree that Thread.currentThread().isInterrupted() check in scheduleExpirationRenewal() is useless.

    I'm glad that we can have the same cognition, and I submitted a PR to remove this unnecessary check from this very important method..

  5. HJK181 commented on Jan 26, 2024

    @HJK181

    We've recently updated to Spring Boot 3.2 with Java 21's Virtual Thread. Since then, we have experienced issues within our application's Gateway. We have a CustomServiceInstanceListSupplier that uses Redisson's RMapCache to sync some information between multiple instances. Small snippet of the code

    RMapCache<String, Integer> tenantToServerCache = redissonClient.getMapCache("somename");
    // Multiple threads can call this simultaneously ...
    RLock lock = tenantToServerCache.getLock(tenant);
    lock.lock();
    try {
    ...
    }
    finally {
      lock.unlock();
    }
    

    This leads to:

    org.redisson.client.RedisException: java.lang.InterruptedException
            at org.redisson.command.CommandAsyncService.get(CommandAsyncService.java:148)
            at org.redisson.RedissonObject.get(RedissonObject.java:90)
            at org.redisson.RedissonLock.tryAcquire(RedissonLock.java:152)
            at org.redisson.RedissonLock.lock(RedissonLock.java:104)
            at org.redisson.RedissonLock.lock(RedissonLock.java:85)
            at io.searchhub.loadbalancer.CustomServiceInstanceListSupplier.selectInstances(CustomServiceInstanceListSupplier.java:100)
            at io.searchhub.loadbalancer.CustomServiceInstanceListSupplier.lambda$get$0(CustomServiceInstanceListSupplier.java:78)
            at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:106)
            at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:98)
            at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:44)
            at reactor.core.publisher.FluxFlattenIterable$FlattenIterableSubscriber.drainAsync(FluxFlattenIterable.java:453)
            at reactor.core.publisher.FluxFlattenIterable$FlattenIterableSubscriber.drain(FluxFlattenIterable.java:724)
            at reactor.core.publisher.FluxFlattenIterable$FlattenIterableSubscriber.onNext(FluxFlattenIterable.java:256)
            at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:74)
            at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondComplete(MonoFlatMap.java:245)
            at reactor.core.publisher.MonoFlatMap$FlatMapInner.onNext(MonoFlatMap.java:305)
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.complete(MonoIgnoreThen.java:294)
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onNext(MonoIgnoreThen.java:188)
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:237)
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onComplete(MonoIgnoreThen.java:204)
            at reactor.core.publisher.MonoIgnoreElements$IgnoreElementsSubscriber.onComplete(MonoIgnoreElements.java:89)
            at reactor.core.publisher.FluxPeek$PeekSubscriber.onComplete(FluxPeek.java:260)
            at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onComplete(FluxDematerialize.java:121)
            at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:91)
            at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:44)
            at reactor.core.publisher.FluxIterable$IterableSubscription.fastPath(FluxIterable.java:402)
            at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:291)
            at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.request(FluxDematerialize.java:127)
            at reactor.core.publisher.FluxPeek$PeekSubscriber.request(FluxPeek.java:138)
            at reactor.core.publisher.MonoIgnoreElements$IgnoreElementsSubscriber.onSubscribe(MonoIgnoreElements.java:72)
            at reactor.core.publisher.FluxPeek$PeekSubscriber.onSubscribe(FluxPeek.java:171)
            at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onSubscribe(FluxDematerialize.java:77)
            at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:201)
            at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:83)
            at reactor.core.publisher.Mono.subscribe(Mono.java:4512)
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:265)
            at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51)
            at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:165)
            at reactor.core.publisher.Operators$BaseFluxToMonoOperator.completePossiblyEmpty(Operators.java:2097)
            at reactor.core.publisher.MonoCollectList$MonoCollectListSubscriber.onComplete(MonoCollectList.java:118)
            at reactor.core.publisher.DrainUtils.postCompleteDrain(DrainUtils.java:132)
            at reactor.core.publisher.DrainUtils.postComplete(DrainUtils.java:187)
            at reactor.core.publisher.FluxMaterialize$MaterializeSubscriber.onComplete(FluxMaterialize.java:141)
            at reactor.core.publisher.FluxLimitRequest$FluxLimitRequestSubscriber.onNext(FluxLimitRequest.java:104)
            at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79)
            at reactor.core.publisher.SerializedSubscriber.onNext(SerializedSubscriber.java:99)
            at reactor.core.publisher.FluxTimeout$TimeoutMainSubscriber.onNext(FluxTimeout.java:181)
            at reactor.core.publisher.Operators$BaseFluxToMonoOperator.completePossiblyEmpty(Operators.java:2097)
            at reactor.core.publisher.MonoCollectList$MonoCollectListSubscriber.onComplete(MonoCollectList.java:118)
            at org.springframework.cloud.commons.publisher.FluxFirstNonEmptyEmitting$FirstNonEmptyEmittingSubscriber.onComplete(FluxFirstNonEmptyEmitting.java:325)
            at reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.onComplete(FluxSubscribeOn.java:166)
     at reactor.core.publisher.FluxIterable$IterableSubscription.fastPath(FluxIterable.java:424)
            at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:291)
            at reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.requestUpstream(FluxSubscribeOn.java:131)
            at reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.onSubscribe(FluxSubscribeOn.java:124)
            at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:201)
            at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:83)
            at reactor.core.publisher.FluxDefer.subscribe(FluxDefer.java:54)
            at reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.run(FluxSubscribeOn.java:194)
            at reactor.core.scheduler.BoundedElasticThreadPerTaskScheduler$SchedulerTask.run(BoundedElasticThreadPerTaskScheduler.java:1013)
            at java.base/java.lang.VirtualThread.run(Unknown Source)
    Caused by: java.lang.InterruptedException: null
            at java.base/java.util.concurrent.CompletableFuture.reportGet(Unknown Source)
            at java.base/java.util.concurrent.CompletableFuture.get(Unknown Source)
            at org.redisson.command.CommandAsyncService.get(CommandAsyncService.java:144)
            ... 60 common frames omitted
    

    I could also find a lock in Redis which got renewed all the time w/o ever expiaring. I've tried to fix it by calling getLock(5, ChronoUnit.SECONDS, but I'm still acting those interrupts. Is this caused by Java's VirtualThreads and the fact that Redis puts the locks with the current Thread name?

    This happens on the newest release 3.26.0

  6. mrniko commented on Jan 26, 2024

    @mrniko
    Member

    You call the code from reactor. I think they interrupt the thread since it blocks the call. Try to use RLockReactive instead.

  7. added this to the 3.23.x milestone on Jan 26, 2024
  8. HJK181 commented on Jan 26, 2024

    @HJK181

    You call the code from reactor. I think they interrupt the thread since it blocks the call. Try to use RLockReactive instead.

    I'll give it a try, but the code worked before while it was also called from reactor.

  9. HJK181 commented on Jan 26, 2024

    @HJK181

    Result of reactive tests:

    lock.tryLock(100, timeoutDuration.toMillis() / 2, TimeUnit.MILLISECONDS)
                    .flatMap(lockAquired -> {
                       ...
                    })
                    .doFinally((bla) -> {
                        lock.unlock().subscribe();
                    });
    

    gives me

    reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id: 13da7223-da92-4369-9e01-9d695ab8881a thread-id: 132
    Caused by: java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id: 13da7223-da92-4369-9e01-9d695ab8881a thread-id: 132
    	at org.redisson.RedissonBaseLock.lambda$unlockAsync0$2(RedissonBaseLock.java:301)
    	Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
    Assembly trace from producer [reactor.core.publisher.FluxCreate] :
    	reactor.core.publisher.Flux.create(Flux.java:649)
    	org.redisson.reactive.CommandReactiveService.reactive(CommandReactiveService.java:47)
    Error has been observed at the following site(s):
    	*__Flux.create ⇢ at org.redisson.reactive.CommandReactiveService.reactive(CommandReactiveService.java:47)
    	|_   Flux.next ⇢ at org.redisson.reactive.CommandReactiveService.reactive(CommandReactiveService.java:76)
    Original Stack Trace:
    		at org.redisson.RedissonBaseLock.lambda$unlockAsync0$2(RedissonBaseLock.java:301)
    		at java.base/java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:934)
    		at java.base/java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:911)
    		at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    		at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2179)
    		at org.redisson.command.CommandBatchService.lambda$executeAsync$7(CommandBatchService.java:371)
    		at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    		at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    		at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    		at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2179)
    		at org.redisson.command.CommandBatchService.lambda$execute$9(CommandBatchService.java:486)
    		at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    		at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    		at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    		at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2179)
    		at org.redisson.command.RedisExecutor.handleSuccess(RedisExecutor.java:625)
    		at org.redisson.command.RedisCommonBatchExecutor.handleResult(RedisCommonBatchExecutor.java:177)
    		at org.redisson.command.RedisExecutor.checkAttemptPromise(RedisExecutor.java:583)
    		at org.redisson.command.RedisExecutor.lambda$execute$5(RedisExecutor.java:196)
    		at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    		at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    		at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    		at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2179)
    		at org.redisson.client.handler.CommandDecoder.decodeCommandBatch(CommandDecoder.java:337)
    		at org.redisson.client.handler.CommandDecoder.decodeCommand(CommandDecoder.java:228)
    		at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:144)
    		at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:120)
    		at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:529)
    		at io.netty.handler.codec.ReplayingDecoder.callDecode(ReplayingDecoder.java:366)
    		at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:290)
    		at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444)
    		at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
    		at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
    		at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
    		at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440)
    		at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
    		at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
    		at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
    		at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788)
    		at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724)
    		at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650)
    		at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562)
    		at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
    		at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    		at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    		at java.base/java.lang.Thread.run(Thread.java:1583)
    

    However, the error is gone if I capture the current Thread id before acquiring the log while also passing that ID to unlock.

     long id = Thread.currentThread().getId();
     lock.tryLock(100, timeoutDuration.toMillis() / 2, TimeUnit.MILLISECONDS)
                    .flatMap(lockAquired -> {
                       ...
                    })
                    .doFinally((bla) -> {
                        lock.unlock(id).subscribe();
                    });
    
  10. HJK181 commented on Jan 29, 2024

    @HJK181

    @mrniko Any idea why this is the behavior of the code executed in Spring-Cloud-Gateway with Virtual Threads

    long id = Thread.currentThread().getId();
    log.debug("ID Top {}", id);
    lock.tryLock(100, timeoutDuration.toMillis() / 2, TimeUnit.MILLISECONDS)
                  .flatMap(lockAquired -> {
                     log.debug("ID flatMap {}", Thread.currentThread().getId());
                     log.debug("LOCK ACQUIRED: {}", lockAquired);
                  })
                  .doFinally((bla) -> {
                     log.debug("IDfinally {}", Thread.currentThread().getId());
                     lock.unlock(id).subscribe();
                  });
    ....
    2024-01-26T15:35:43.422Z DEBUG 1 --- [gateway] [sson-netty-3-11] .CustomServiceInstanceListSupplier : IDfinally 51
    2024-01-26T15:35:46.171Z DEBUG 1 --- [gateway] [ndedElastic-760] .CustomServiceInstanceListSupplier : ID Top 915
    2024-01-26T15:35:46.174Z DEBUG 1 --- [gateway] [sson-netty-3-17] .CustomServiceInstanceListSupplier : ID flatMap 63
    2024-01-26T15:35:46.174Z DEBUG 1 --- [gateway] [sson-netty-3-17] .SmartsuggestServiceInstanceListSupplier : LOCK ACQUIRED: true
    

    while the order is different when using some Gist:

    long id = Thread.currentThread().getId();
    log.debug("ID Top {}", id);
    Flux.just(emptyList())
      .flatMap(list -> Mono.defer(() -> {
    	  try {
    		  Thread.sleep(1000);
    	  }
    	  catch (InterruptedException e) {
    		  throw new RuntimeException(e);
    	  }
    	  return Mono.just(list);
      }))
      .flatMap(list -> {
    	   log.debug("ID flatMap {}", Thread.currentThread().getId());
    	  return Mono.just(list);
      })
      .doFinally(list ->   log.debug("IDfinally {}", Thread.currentThread().getId()))
      .subscribe();
      ...
      ID Top 1
      ID flatMap 1
      IDfinally 1
    

    The finally block gets executed first, even though that's the recommended way here: https://github.com/redisson/redisson/wiki/8.-Distributed-locks-and-synchronizers

  11. seakider commented on Apr 14, 2025

    @seakider
    Contributor

    @HJK181

    lock.tryLock(100, timeoutDuration.toMillis() / 2, TimeUnit.MILLISECONDS)

    According to the Reactive interface code example in the documentation, you should use the interface parameterized with threadId when acquiring or unlocking a lock.

    As for your question about the order, I don't think it should be relevant to redisson.

  12. removed this from the 3.23.x milestone on Jul 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions