karlseguin / ccache

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

Support for OnDelete() callback #16

Closed alexejk closed 6 years ago

alexejk commented 6 years ago

While using this cache i've hit a block where I needed to ensure the item being removed from the cache stops its internal go-routine (basically a Close()). Without closing the resources - cached items will never be cleared by GC.

This PR allows doing just that by registering a callback for removal via Configuration.OnRemove().

For example:

// MyCloseable is a sample Item we will put in cache that might need more cleanup
type MyCloseable struct{}
func NewCloseable() *MyCloseable{
  c := &MyCloseable{}
  // Do something else, such as start go routines

  return c
}
func (c *MyCloseable) Close() {
  // Clean-up resources, e.g stop go routines
}

---

// Support function that will be used as a callback
func cleanupCloseable(item *ccache.Item) {

  // Do something to cleanup, e.g call Close()
  closeable := item.Value().(*MyCloseable)
  closeable.Close()
}

func main() {
  c := ccache.New(Configure().OnDelete(cleanupCloseable))
  c.Set("one", NewCloseable())

  // After some time ...
  c.Delete("one")
}

Tests are updated to ensure function is called on both layered cache and standard impl.

Additionally as part of this PR I've made it dep-friendly by supporting vendoring and locking versions to ensure proper dependency management. https://github.com/golang/dep

karlseguin commented 6 years ago

Feature sounds reasonable, I'll look at the PR in detail this weekend.