Skip to content

Commit be0661c

Browse files
authored
Merge pull request rails#51132 from tonytonyjan/docs/fix-fetch-example
Improve the example of ActiveSupport::Cache::Store#fetch
2 parents 05b4db2 + a8bc63a commit be0661c

File tree

1 file changed

+31
-15
lines changed
  • activesupport/lib/active_support

1 file changed

+31
-15
lines changed

activesupport/lib/active_support/cache.rb

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -405,31 +405,47 @@ def mute
405405
# has elapsed.
406406
#
407407
# # Set all values to expire after one minute.
408-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)
408+
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1)
409409
#
410-
# cache.write('foo', 'original value')
410+
# cache.write("foo", "original value")
411411
# val_1 = nil
412412
# val_2 = nil
413-
# sleep 60
413+
# p cache.read("foo") # => "original value"
414414
#
415-
# Thread.new do
416-
# val_1 = cache.fetch('foo', race_condition_ttl: 10.seconds) do
415+
# sleep 1 # wait until the cache expires
416+
#
417+
# t1 = Thread.new do
418+
# # fetch does the following:
419+
# # 1. gets an recent expired entry
420+
# # 2. extends the expiry by 2 seconds (race_condition_ttl)
421+
# # 3. regenerates the new value
422+
# val_1 = cache.fetch("foo", race_condition_ttl: 2) do
417423
# sleep 1
418-
# 'new value 1'
424+
# "new value 1"
419425
# end
420426
# end
421427
#
422-
# Thread.new do
423-
# val_2 = cache.fetch('foo', race_condition_ttl: 10.seconds) do
424-
# 'new value 2'
425-
# end
428+
# # Wait until t1 extends the expiry of the entry
429+
# # but before generating the new value
430+
# sleep 0.1
431+
#
432+
# val_2 = cache.fetch("foo", race_condition_ttl: 2) do
433+
# # This block won't be executed because t1 extended the expiry
434+
# "new value 2"
426435
# end
427436
#
428-
# cache.fetch('foo') # => "original value"
429-
# sleep 10 # First thread extended the life of cache by another 10 seconds
430-
# cache.fetch('foo') # => "new value 1"
431-
# val_1 # => "new value 1"
432-
# val_2 # => "original value"
437+
# t1.join
438+
#
439+
# p val_1 # => "new value 1"
440+
# p val_2 # => "oritinal value"
441+
# p cache.fetch("foo") # => "new value 1"
442+
#
443+
# # The entry requires 3 seconds to expire (expires_in + race_condition_ttl)
444+
# # We have waited 2 seconds already (sleep(1) + t1.join) thus we need to wait 1
445+
# # more second to see the entry expire.
446+
# sleep 1
447+
#
448+
# p cache.fetch("foo") # => nil
433449
#
434450
# ==== Dynamic Options
435451
#

0 commit comments

Comments
 (0)