Skip to content

Commit

Permalink
mutex in cache
Browse files Browse the repository at this point in the history
  • Loading branch information
snichme authored and Your Name committed Jan 23, 2025
1 parent 6c84005 commit 439306f
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/lavinmq/deduplication.cr
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,27 @@ module LavinMQ

class MemoryCache(T) < Cache(T)
def initialize(@size : UInt32)
@lock = Mutex.new
@store = Hash(T, Time::Span?).new(initial_capacity: @size)
end

def contains?(key : T) : Bool
return false unless @store.has_key?(key)
ttd = @store[key]
return true unless ttd
return true if ttd > RoughTime.monotonic
@store.delete(key)
false
@lock.synchronize do
return false unless @store.has_key?(key)
ttd = @store[key]
return true unless ttd
return true if ttd > RoughTime.monotonic
@store.delete(key)
false
end
end

def insert(key : T, ttl : UInt32? = nil)
@store.shift if @store.size >= @size
val = ttl.try { |v| RoughTime.monotonic + v.milliseconds }
@store[key] = val
@lock.synchronize do
@store.shift if @store.size >= @size
val = ttl.try { |v| RoughTime.monotonic + v.milliseconds }
@store[key] = val
end
end
end

Expand Down

0 comments on commit 439306f

Please sign in to comment.