goburrow / cache

Mango Cache 🥭 - Partial implementation of Guava Cache in Go (golang).
BSD 3-Clause "New" or "Revised" License
574 stars 48 forks source link

WithRemovalListener calls callback on the newer value #31

Open JakobJoonas opened 2 years ago

JakobJoonas commented 2 years ago

Hey, I encountered an issue where RemovalListener callback is called with the new value instead of the one that was expired, this should not be happening am I correct?

Here is a simple test case

func TestCache(t *testing.T) {
    ch := make(chan int)

    dbCache := cache.New(
        cache.WithRemovalListener(func(k cache.Key, v cache.Value) {
            // We are expecting a delete event to Server 0
            // But this test fails because value is Server 1 not Server 0
            assert.Equal(t, "Server 0", v.(string))
            ch <- 1
        }),
        cache.WithExpireAfterAccess(200*time.Millisecond),
    )

    dbCache.Put("key", "Server 0")

    // Wait for cache to expire.
    time.Sleep(time.Millisecond * 200)

    // cache should now be expired, meaning GetIfPresent should not return a value.
    _, exists := dbCache.GetIfPresent("key")
    assert.False(t, exists)

    // Add a new value into the same key
    dbCache.Put("key", "Server 1")
    <-ch
}