Thread-safe (Goroutine-safe) cache in Go
===

**Question 1**

I am building/searching for a RAM memory cache layer for my server. It is a simple LRU cache that needs to handle concurrent requests (both Gets an Sets).

I have found https://github.com/pmylund/go-cache claiming to be thread safe.

This is true as far as getting the stored interface. But if multiple goroutines requests the same data, they are all retrieving a pointer (stored in the interface) to the same block of memory. If any goroutine changes the data, this is no longer very safe.

*Are there any cache-packages out there that tackles this problem?*


----------

**Question 1.1**

If the answer to *Question 1* is *No*, then what would be the suggested solution?  
I see two options:

*Alternative 1*  
*Solution:* Storing the values in a wrapping struct with a `sync.Mutex` so that each goroutine needs to lock the data before reading/writing to it.  
`type cacheElement struct { value interface{}, lock sync.Mutex }`  
*Drawbacks:* The cache becomes unaware of changes made to data or might even have dropped it out of the cache. One goroutine might also lock others.

*Alternative 2*  
*Solution:* Make a copy of the data (assuming the data in itself doesn't contain pointers)  
*Drawbacks:* Memory allocation every time a cache Get is performed, more garbage collection.

---

Sorry for the multipart question. But you don't have to answer all of them. If you have a good answer to Question 1, that would be sufficient for me!
