Guest User

Untitled

a guest
Apr 25th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. def get_cached_object(cache_key)
  2. expensive_object = Memcached.get cache_key
  3.  
  4. if expensive_object == typeof(ExpensiveObject)
  5. return expensive_object
  6. elsif expensive_object == null
  7. # try to "add" the cache_key, setting the value to a
  8. # timeout during which all other threads will wait and
  9. # poll; note that add only sets the value if no key exists yet
  10. we_set_it = Memcached.add cache_key, Time.now + 5.seconds
  11. if we_set_it
  12. # go build expensive_object, then set it in the cache
  13. Memcached.set cache_key, expensive_object
  14. return expensive_object
  15. end
  16. end
  17.  
  18. # we're not building the object, someone else is;
  19. # poll and sleep until it is ready or we timeout
  20. timeout = expensive_object
  21. while (Time.now < timeout)
  22. expensive_object = Memcached.get cache_key
  23. if expensive_object == typeof(ExpensiveObject)
  24. return expensive_object
  25. end
  26. sleep(300) # ms
  27. end
  28. throw TimeoutException
  29. end
Add Comment
Please, Sign In to add comment