@@ -35,34 +35,31 @@ func NewCache(max int) *Cache {
35
35
func (c * Cache ) Add (key uint64 , value * MetricState ) {
36
36
c .mtx .Lock ()
37
37
defer c .mtx .Unlock ()
38
- if ee , ok := c .cache [key ]; ok {
39
- c .free .Remove (ee )
40
- //check if element was already in list and if not push to front
41
- c .used .MoveToFront (ee )
42
- if c .used .Front () != ee {
43
- c .used .PushFront (ee )
44
- }
45
- ee .Value .(* entry ).value = value
46
- return
38
+ if ele , ok := c .cache [key ]; ok {
39
+ //deleting from both lists as a workaround to not knowing which list actually contains the elem
40
+ //if the elem is not present in the list Remove won't do anything
41
+ // Remove clears ele's head,prev and next pointers so it can't be reused
42
+ c .free .Remove (ele )
43
+ c .used .Remove (ele )
47
44
}
48
- ele := c .used .PushFront (& entry {key , value })
49
- c .cache [key ] = ele
45
+ c .cache [key ] = c .used .PushFront (& entry {key , value })
50
46
if c .maxEntries != 0 && c .free .Len ()+ c .used .Len () > c .maxEntries {
51
47
c .removeOldest ()
52
48
}
49
+
53
50
}
54
51
55
52
// Get looks up a key's value from the cache.
56
53
func (c * Cache ) Get (key uint64 ) (value * MetricState , ok bool ) {
57
54
c .mtx .Lock ()
58
55
defer c .mtx .Unlock ()
59
56
if ele , hit := c .cache [key ]; hit {
57
+ //deleting from both lists as a workaround to not knowing which list actually contains the elem
58
+ //if the elem is not present in the list Remove won't do anything
59
+ // Remove clears ele's head,prev and next pointers so it can't be reused
60
60
c .free .Remove (ele )
61
- //check if element was already in list and if not push to front
62
- c .used .MoveToFront (ele )
63
- if c .used .Front () != ele {
64
- c .used .PushFront (ele )
65
- }
61
+ c .used .Remove (ele )
62
+ c .cache [key ] = c .used .PushFront (& entry {key , ele .Value .(* entry ).value })
66
63
return ele .Value .(* entry ).value , true
67
64
}
68
65
return
@@ -73,8 +70,7 @@ func (c *Cache) removeOldest() {
73
70
ele := c .free .Back ()
74
71
if ele != nil {
75
72
c .free .Remove (ele )
76
- kv := ele .Value .(* clist.Element ).Value .(* entry )
77
- delete (c .cache , kv .key )
73
+ delete (c .cache , ele .Value .(* entry ).key )
78
74
return
79
75
}
80
76
c .cond .Wait ()
@@ -85,8 +81,12 @@ func (c *Cache) ResetMetric(key uint64) {
85
81
c .mtx .Lock ()
86
82
defer c .mtx .Unlock ()
87
83
if ele , ok := c .cache [key ]; ok {
84
+ //deleting from both lists as a workaround to not knowing which list actually contains the elem
85
+ //if the elem is not present in the list Remove won't do anything
86
+ // Remove clears ele's head,prev and next pointers so it can't be reused
88
87
c .used .Remove (ele )
89
- c .free .PushFront (ele )
88
+ c .free .Remove (ele )
89
+ c .cache [key ] = c .free .PushFront (& entry {key , ele .Value .(* entry ).value })
90
90
c .cond .Signal ()
91
91
}
92
92
}
0 commit comments