AdoccaMemcache 0.1.3 → 0.1.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (3) hide show
  1. data/Rakefile +1 -1
  2. data/lib/am_memcache.rb +36 -11
  3. metadata +2 -2
data/Rakefile CHANGED
@@ -4,7 +4,7 @@ require 'rubygems'
4
4
  require 'hoe'
5
5
  require './lib/adocca_memcache.rb'
6
6
 
7
- Hoe.new('AdoccaMemcache', '0.1.3') do |p|
7
+ Hoe.new('AdoccaMemcache', '0.1.4') do |p|
8
8
  p.rubyforge_name = 'adocca-plugins'
9
9
  p.author = 'adocca Entertainment AB'
10
10
  p.summary = 'A client library to simplify using memcached with Ruby on Rails projects.'
@@ -279,25 +279,50 @@ module Adocca
279
279
  # lock expiry time
280
280
  TRANS_EXPTIME = 10
281
281
  TRANS_MAX_TRIES = 10
282
-
283
- # memcache-driven transaction mechanism
284
- def synchronize(key)
282
+
283
+ #
284
+ # Will create a reentrant lock on +key+, but waiting no more than +timeout+
285
+ # for the lock. Will sleep 1 second between each try.
286
+ #
287
+ # Will return whether the locking was successful.
288
+ #
289
+ def lock(key, options = {})
290
+ timeout = options[:timeout] || 1 << 32
291
+ expire = options[:expire] || 0
285
292
  cache_key = make_cache_key(key)
286
- tries = 0
293
+ start_at = Time.now
287
294
  we_locked_now = false
288
295
  we_locked_earlier = false
289
296
  ok_value = "#{HOST_HASH}:#{Thread.current.object_id}"
290
- while (!(we_locked_now = add(cache_key, ok_value, TRANS_EXPTIME)) &&
297
+ while (!(we_locked_now = add(cache_key, ok_value, expire)) &&
291
298
  !(we_locked_earlier = (get(cache_key) == ok_value)) &&
292
- tries < TRANS_MAX_TRIES)
299
+ Time.now < start_at + timeout)
293
300
  sleep 1
294
- tries += 1
295
301
  end
296
- if we_locked_now || we_locked_earlier
297
- yield
298
- self.delete(cache_key) if we_locked_now
302
+ return we_locked_now || we_locked_earlier
303
+ end
304
+
305
+ #
306
+ # Will release any lock on +key+.
307
+ #
308
+ def unlock(key)
309
+ self.delete(make_cache_key(key))
310
+ end
311
+
312
+ #
313
+ # memcache-driven locking mechanism
314
+ #
315
+ # Uses <i>lock</i> and <i>unlock</i>
316
+ #
317
+ def synchronize(key, &block)
318
+ if lock_success = lock(key, :expire => TRANS_EXPTIME, :timeout => TRANS_MAX_TRIES)
319
+ begin
320
+ yield
321
+ ensure
322
+ unlock(key)
323
+ end
299
324
  else
300
- raise MemCacheError, "Couldn't obtain lock"
325
+ raise MemCacheError, "Couldn't obtain lock on #{key}"
301
326
  end
302
327
  end
303
328
 
metadata CHANGED
@@ -3,8 +3,8 @@ rubygems_version: 0.8.11
3
3
  specification_version: 1
4
4
  name: AdoccaMemcache
5
5
  version: !ruby/object:Gem::Version
6
- version: 0.1.3
7
- date: 2006-12-22 00:00:00 +01:00
6
+ version: 0.1.4
7
+ date: 2007-01-17 00:00:00 +01:00
8
8
  summary: A client library to simplify using memcached with Ruby on Rails projects.
9
9
  require_paths:
10
10
  - lib