diff --git a/lib/redis/semaphore.rb b/lib/redis/semaphore.rb index 5f7c639..11eaf62 100644 --- a/lib/redis/semaphore.rb +++ b/lib/redis/semaphore.rb @@ -36,7 +36,7 @@ def exists_or_create! if token == API_VERSION && @redis.get(version_key).nil? @redis.set(version_key, API_VERSION) end - + set_expiration_if_necessary true end end @@ -163,8 +163,6 @@ def simple_mutex(key_name, expires = nil) end def create! - @redis.expire(exists_key, 10) - @redis.multi do @redis.del(grabbed_key) @redis.del(available_key) @@ -173,7 +171,6 @@ def create! end @redis.set(version_key, API_VERSION) @redis.persist(exists_key) - set_expiration_if_necessary end end diff --git a/spec/semaphore_spec.rb b/spec/semaphore_spec.rb index 4d7e0b1..3a36771 100644 --- a/spec/semaphore_spec.rb +++ b/spec/semaphore_spec.rb @@ -160,6 +160,33 @@ sleep 3.0 expect(@redis.keys.count).to eq(original_key_size) end + + it "does not leave a key without expiration if expiration given" do + queue = Queue.new + threads = Array.new(2) do + Thread.new do + opts = { redis: @redis, expiration: 3 } + Redis::Semaphore.new(:my_semaphore, opts).lock(5) do + sleep 1 + end + end + end + sleep 4.0 + @redis2 = Redis.new db: 15 + threads.each(&:kill) # ensure signal step fails + exist_key = @redis2.ttl("SEMAPHORE:my_semaphore:EXISTS").to_s + expect(exist_key).to_not eql("-1") + sleep 4.0 # allow blpop timeout to occur + thrd = Thread.new do + opts = { redis: @redis2, expiration: 3 } + Redis::Semaphore.new(:my_semaphore, opts).lock(5) do + queue << "work" + end + end + thrd.join(3) + expect(queue.size).to eql(1) + expect(@redis.ttl("SEMAPHORE:my_semaphore:EXISTS").to_s).to_not eql("-1") + end end describe "semaphore without staleness checking" do