Skip to content

Commit

Permalink
[#44] Fix issues with concurrent updates in DeleteByFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
maypok86 committed Feb 6, 2024
1 parent 9ad06bc commit bab79db
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
28 changes: 17 additions & 11 deletions internal/core/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,20 +232,26 @@ func (c *Cache[K, V]) Delete(key K) {
}
}

func (c *Cache[K, V]) deleteNode(n *node.Node[K, V]) {
deleted := c.hashmap.DeleteNode(n)
if deleted != nil {
c.writeBuffer.Insert(node.NewDeleteTask(deleted))
}
}

// DeleteByFunc removes the association for this key from the cache when the given function returns true.
func (c *Cache[K, V]) DeleteByFunc(f func(key K, value V) bool) {
// TODO(maypok86): This function can be implemented more efficiently, if the performance of this implementation is not enough for you, then come with an issue :)
var keysToDelete []K
c.Range(func(key K, value V) bool {
if f(key, value) {
keysToDelete = append(keysToDelete, key)
c.hashmap.Range(func(n *node.Node[K, V]) bool {
if n.IsExpired() {
return true
}

if f(n.Key(), n.Value()) {
c.deleteNode(n)
}

return true
})

for _, key := range keysToDelete {
c.Delete(key)
}
}

func (c *Cache[K, V]) cleanup() {
Expand All @@ -264,7 +270,7 @@ func (c *Cache[K, V]) cleanup() {
c.evictionMutex.Unlock()

for _, n := range e {
c.hashmap.EvictNode(n)
c.hashmap.DeleteNode(n)
}

expired = clearBuffer(expired)
Expand Down Expand Up @@ -325,7 +331,7 @@ func (c *Cache[K, V]) process() {
c.evictionMutex.Unlock()

for _, n := range d {
c.hashmap.EvictNode(n)
c.hashmap.DeleteNode(n)
}

buffer = clearBuffer(buffer)
Expand Down
4 changes: 2 additions & 2 deletions internal/hashtable/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,10 +296,10 @@ func (m *Map[K, V]) Delete(key K) *node.Node[K, V] {
})
}

// EvictNode evicts the node for a key.
// DeleteNode evicts the node for a key.
//
// Returns the evicted node or nil if the node wasn't evicted.
func (m *Map[K, V]) EvictNode(n *node.Node[K, V]) *node.Node[K, V] {
func (m *Map[K, V]) DeleteNode(n *node.Node[K, V]) *node.Node[K, V] {
return m.delete(n.Key(), func(current *node.Node[K, V]) bool {
return n == current
})
Expand Down

0 comments on commit bab79db

Please sign in to comment.