Andy5
Andy5

Reputation: 2415

How to create a Singleton Cache in Go

I am working in Golang, which I am new to, and I have come across two interesting articles:

https://hackernoon.com/in-memory-caching-in-golang

The one from hackernoon is really good and the first example (Simple Map) is precisely what I am for to create a cache as it gives an example for expiring values in a cache. Where I am struggling to understand, is that it does not say whether the implementation creates just one instantation of the cache and not multiple copies, which would conflict or you have one value in one copy and one in another, and the look ups won't work properly.

In another link https://thedevelopercafe.com/articles/singleton-in-golang-839d8610958b it talks about instantation of one cache.

So, my question in both they use sync and so can I ask someone who has experience in Golang to advise me whether the example from Hackernoon in the function called newlocalcache sets up a singleton and if not what do I need to do to add it?

Upvotes: 0

Views: 513

Answers (1)

mkopriva
mkopriva

Reputation: 38343

the function called newlocalcache sets up a singleton

No, it constructs and returns a new local cache every time it's called.

if not what do I need to do to add it?

Call it just once. For example:

var localCacheSingleton *localCache

var newLocalCacheOnce sync.Once

func newLocalCache(cleanupInterval time.Duration) *localCache {
    newLocalCacheOnce.Do(func() {
        lc := &localCache{
            users: make(map[int64]cachedUser),
            stop:  make(chan struct{}),
        }

        lc.wg.Add(1)
        go func(cleanupInterval time.Duration) {
            defer lc.wg.Done()
            lc.cleanupLoop(cleanupInterval)
        }(cleanupInterval)

        localCacheSingleton = lc
    })
    return localCacheSingleton
}

Upvotes: 1

Related Questions