Skip to content

Commit

Permalink
fix try_lock to fail earlier
Browse files Browse the repository at this point in the history
  • Loading branch information
jakedouglas committed Sep 15, 2010
1 parent 7858df2 commit a6f433d
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/cassandra_lock.rb
Expand Up @@ -107,7 +107,13 @@ def lock
end

def try_lock
worker_count, my_number = get_worker_count_and_current_number(@lock_id, @my_worker_id)
worker_count, my_number = get_worker_count_and_current_number(@lock_id, @my_worker_id, true)

# bail early if someone was already holding/waiting
unless my_number
return false
end

lock_acquired = acquire(@lock_id, worker_count, my_number, @my_worker_id, false)

unless lock_acquired
Expand Down Expand Up @@ -162,14 +168,23 @@ def acquire(lock_id, worker_count, my_number, my_worker_id, should_wait)
true
end

def get_worker_count_and_current_number(lock_id, worker_id)
def get_worker_count_and_current_number(lock_id, worker_id, fail_fast=false)
worker_id = worker_id.to_s

# indicate that we are in the process of picking a number
set(CHOOSING, lock_id, { worker_id => TRUE })

# get the current highest number, add 1, insert it as our number
numbers = get(NUMBERS, lock_id)

# for try_lock, just bail if anyone is holding/waiting
if fail_fast
if numbers.values.any?{|v| v != "0" }
set(CHOOSING, lock_id, { worker_id => FALSE })
return false
end
end

my_number = numbers.values.map{|n| n.to_i }.max + 1
set(NUMBERS, lock_id, { worker_id => my_number.to_s })

Expand Down

0 comments on commit a6f433d

Please sign in to comment.