redisson icon indicating copy to clipboard operation
redisson copied to clipboard

Non-reentrant locks

Open borisdainson opened this issue 3 years ago • 1 comments

Hi. RedissonLock and other Redisson lock implementations I saw so far are all reentrant. For my use case I need non-reentrant lock. A semaphore would do the job but it does not get auto-released when application dies (I asked about that a few days ago). Any suggestions for non-reentrant locks?

borisdainson avatar Aug 05 '22 20:08 borisdainson

Do you see any issues with an extension of RedissonLock below to make it not reentrant? It works fine for me and I have tests for it. `

public class RedissonNonReentrantLock extends RedissonLock {
    public RedissonNonReentrantLock(CommandAsyncExecutor commandExecutor, String name) {
        super(commandExecutor, name);
    }

    @Override
    String getChannelName() {
        return prefixName("redisson_nonreentrant_lock__channel", getRawName());
    }

    @Override
    <T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
        return evalWriteAsync(getRawName(), LongCodec.INSTANCE, command,
                "if (redis.call('exists', KEYS[1]) == 0) then " +
                        "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
                        "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                        "return nil; " +
                        "end; " +
                        "return redis.call('pttl', KEYS[1]);",
                Collections.singletonList(getRawName()), unit.toMillis(leaseTime), getLockName(threadId));
    }
}

`

borisdainson avatar Aug 30 '22 13:08 borisdainson

@borisdainson FWIW, we also had a use-case for non-reentrant locks and your suggested extension worked well for us.

Umofomia avatar Apr 19 '23 21:04 Umofomia