优化代码

This commit is contained in:
GoEdgeLab
2023-10-11 14:07:13 +08:00
parent bf68c29fa5
commit 0e45e75167
4 changed files with 45 additions and 3 deletions

View File

@@ -24,11 +24,19 @@ func NewPiece[T any](maxItems int) *Piece[T] {
}
func (this *Piece[T]) Add(key uint64, item *Item[T]) (ok bool) {
this.locker.Lock()
this.locker.RLock()
if this.maxItems > 0 && len(this.m) >= this.maxItems {
this.locker.Unlock()
this.locker.RUnlock()
return
}
this.locker.RUnlock()
this.locker.Lock()
oldItem, exists := this.m[key]
if exists && oldItem.expiredAt == item.expiredAt {
this.locker.Unlock()
return true
}
this.m[key] = item
this.locker.Unlock()

View File

@@ -18,6 +18,16 @@ func TestPiece_Add(t *testing.T) {
t.Log(piece.Read(1))
}
func TestPiece_Add_Same(t *testing.T) {
piece := NewPiece[int](10)
piece.Add(1, &Item[int]{expiredAt: time.Now().Unix() + 3600})
piece.Add(1, &Item[int]{expiredAt: time.Now().Unix() + 3600})
for key, item := range piece.m {
t.Log(key, item.Value)
}
t.Log(piece.Read(1))
}
func TestPiece_MaxItems(t *testing.T) {
piece := NewPiece[int](10)
for i := 0; i < 1000; i++ {