delef / maxminddb.cr

MaxMind DB Reader for Crystal
MIT License
23 stars 5 forks source link

Ensuring cache feature is thread safe? #6

Closed 636f7374 closed 4 years ago

636f7374 commented 4 years ago

Summary

Solution

Improve

module MaxMindDB struct Cache(K, V) property capacity : Int32 property storage : Immutable::Map(K, V)

def initialize(@capacity : Int32)
  @storage = Immutable::Map(K, V).new
end

def fetch(key : K, &block : K -> V) : V
  value = storage[key]?
  return value if value

  value = yield key

  unless full?
    _storage = storage.set key, value
    self.storage = _storage
  end

  value
end

def full?
  storage.size >= capacity
end

end end


* [shard.yml](https://github.com/delef/maxminddb.cr/blob/master/shard.yml)

```yaml
dependencies:
  immutable:
    github: lucaong/immutable

References

636f7374 commented 4 years ago

Finally

I just provide it as a reference, if you are interested, you can always improve it yourself.