karlseguin / ccache

A golang LRU Cache for high concurrency
MIT License
1.28k stars 119 forks source link

item == nil, is it true for expired cache.Get("user:4") too? #23

Closed unisqu closed 5 years ago

unisqu commented 5 years ago

item == nil, is it true for expired cache.Get("user:4") too?

  item := cache.Get("user:4")
  if item == nil {
    //handle
  } else {
    user := item.Value().(*User)
  }

i would like to check if item is empty. how do i check that? will expired item be emptied?

karlseguin commented 5 years ago

There's 3 cases:


if item == nil {
   ...
} else if item.Expired() {
  .. // can use item.TTL() to see how stale it is
} else {
   .. / item not expired
}```

The `item.Expired() == true` case happens when the item has expired, but it hasn't been removed from the cache (because the size of the cache is still smaller than the configured max). The benefit of this approach is that it gives you more flexibility by giving you the option to use stale data if you want.
unisqu commented 5 years ago

thx

unisqu commented 5 years ago

if item == nil { ... } else if item.Expired() { .. // can use item.TTL() to see how stale it is } else { .. / item not expired }```

my problem with this statement is... "see how stale it is?" let's say in the next nanosecond, the cache is exceeded and item is evicted/flushed, let's say i dont do TTL() but would like to serve that stale item (but the last nanosecond is evicted/flush), won't that be "dangerous" as my item will be nil.

karlseguin commented 5 years ago

No.

It might get evicted from the cache, but item still holds a reference to value so it won't be garbage collected until item falls out of scope.