Skip to content

Commit

Permalink
Better mem-leak prevention in expirable set
Browse files Browse the repository at this point in the history
  • Loading branch information
ixti committed Nov 19, 2023
1 parent 6fb5e91 commit 48f96ca
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions lib/sidekiq/throttled/expirable_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,14 @@ def initialize(ttl)
# @param element [Object]
# @return [ExpirableSet] self
def add(element)
# cleanup expired elements to avoid mem-leak
horizon = now
expired = @elements.each_pair.select { |(_, sunset)| expired?(sunset, horizon) }
expired.each { |pair| @elements.delete_pair(*pair) }

# add new element
@elements[element] = now + @ttl

self
end

Expand All @@ -40,16 +47,11 @@ def each
return to_enum __method__ unless block_given?

horizon = now
expired = []

@elements.each_pair do |element, sunset|
next yield element if horizon < sunset

expired << [element, sunset]
yield element unless expired?(sunset, horizon)
end

expired.each { |pair| @elements.delete_pair(*pair) }

self
end

Expand All @@ -59,6 +61,10 @@ def each
def now
::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end

def expired?(sunset, horizon)
sunset <= horizon
end
end
end
end

0 comments on commit 48f96ca

Please sign in to comment.