Skip to content

The Get function is not thread-safe. Concurrent calls may lead to race conditions or data corruption. #56

Description

@Ap0k

Describe the bug

func (cache *Cache) Get(key string) (any, bool) {
	cache.mutex.Lock()
	entry, ok := cache.get(key)
	if !ok {
		cache.stats.Misses++
		cache.mutex.Unlock()
		return nil, false
	}
	if entry.Expired() {
		cache.stats.ExpiredKeys++
		cache.delete(key)
		cache.mutex.Unlock()
		return nil, false
	}
	cache.stats.Hits++
	if cache.evictionPolicy == LeastRecentlyUsed {
		entry.Accessed()
		if cache.head == entry {
			cache.mutex.Unlock() // The mutex is released before the work with the shared data has finished.
			return entry.Value, true // !!!RACE detection
		}
		// Because the eviction policy is LRU, we need to move the entry back to HEAD
		cache.moveExistingEntryToHead(entry)
	}
	cache.mutex.Unlock() // The mutex is released before the work with the shared data has finished.
	return entry.Value, true // !!!RACE Detection
}

What do you see?

Better to rewrite the function as follows:

func (cache *Cache) Get(key string) (any, bool) {
	cache.mutex.Lock()
	defer cache.mutex.UnLock()
	entry, ok := cache.get(key)
	if !ok {
		cache.stats.Misses++
		return nil, false
	}
	if entry.Expired() {
		cache.stats.ExpiredKeys++
		cache.delete(key)
		return nil, false
	}
	cache.stats.Hits++
	if cache.evictionPolicy == LeastRecentlyUsed {
		entry.Accessed()
		if cache.head == entry {
			return entry.Value, true
		}
		// Because the eviction policy is LRU, we need to move the entry back to HEAD
		cache.moveExistingEntryToHead(entry)
	}
	return entry.Value, true
}

What do you expect to see?

No response

List the steps that must be taken to reproduce this issue

No response

Version

No response

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions