Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def get_cached_object(cache_key)
- expensive_object = Memcached.get cache_key
- if expensive_object == typeof(ExpensiveObject)
- return expensive_object
- elsif expensive_object == null
- # try to "add" the cache_key, setting the value to a
- # timeout during which all other threads will wait and
- # poll; note that add only sets the value if no key exists yet
- we_set_it = Memcached.add cache_key, Time.now + 5.seconds
- if we_set_it
- # go build expensive_object, then set it in the cache
- Memcached.set cache_key, expensive_object
- return expensive_object
- end
- end
- # we're not building the object, someone else is;
- # poll and sleep until it is ready or we timeout
- timeout = expensive_object
- while (Time.now < timeout)
- expensive_object = Memcached.get cache_key
- if expensive_object == typeof(ExpensiveObject)
- return expensive_object
- end
- sleep(300) # ms
- end
- throw TimeoutException
- end
Add Comment
Please, Sign In to add comment