diff --git a/datastruct/dict/concurrent.go b/datastruct/dict/concurrent.go index fe97618..19bd57d 100644 --- a/datastruct/dict/concurrent.go +++ b/datastruct/dict/concurrent.go @@ -168,6 +168,7 @@ func (dict *ConcurrentDict) Remove(key string) (result int) { if _, ok := shard.m[key]; ok { delete(shard.m, key) + dict.decreaseCount() return 1 } return 0 @@ -177,6 +178,10 @@ func (dict *ConcurrentDict) addCount() int32 { return atomic.AddInt32(&dict.count, 1) } +func (dict *ConcurrentDict) decreaseCount() int32 { + return atomic.AddInt32(&dict.count, -1) +} + // ForEach traversal the dict // it may not visits new entry inserted during traversal func (dict *ConcurrentDict) ForEach(consumer Consumer) { diff --git a/datastruct/dict/concurrent_test.go b/datastruct/dict/concurrent_test.go index 5da4df2..a580783 100644 --- a/datastruct/dict/concurrent_test.go +++ b/datastruct/dict/concurrent_test.go @@ -116,14 +116,17 @@ func TestConcurrentPutIfExists(t *testing.T) { func TestConcurrentRemove(t *testing.T) { d := MakeConcurrent(0) - + totalCount := 100 // remove head node - for i := 0; i < 100; i++ { + for i := 0; i < totalCount; i++ { // insert key := "k" + strconv.Itoa(i) d.Put(key, i) } - for i := 0; i < 100; i++ { + if d.Len()!=totalCount{ + t.Error("put test failed: expected len is 100, actual: " + strconv.Itoa(d.Len())) + } + for i := 0; i < totalCount; i++ { key := "k" + strconv.Itoa(i) val, ok := d.Get(key) @@ -140,6 +143,9 @@ func TestConcurrentRemove(t *testing.T) { if ret != 1 { t.Error("remove test failed: expected result 1, actual: " + strconv.Itoa(ret) + ", key:" + key) } + if d.Len()!=totalCount-i-1{ + t.Error("put test failed: expected len is 99, actual: " + strconv.Itoa(d.Len())) + } _, ok = d.Get(key) if ok { t.Error("remove test failed: expected true, actual false") @@ -148,6 +154,9 @@ func TestConcurrentRemove(t *testing.T) { if ret != 0 { t.Error("remove test failed: expected result 0 actual: " + strconv.Itoa(ret)) } + if d.Len()!=totalCount-i-1{ + t.Error("put test failed: expected len is 99, actual: " + strconv.Itoa(d.Len())) + } } // remove tail node