diff --git a/pkg/storage/volatilitymonitor/volatility_data.go b/pkg/storage/volatilitymonitor/volatility_data.go index 67755b8..020d590 100644 --- a/pkg/storage/volatilitymonitor/volatility_data.go +++ b/pkg/storage/volatilitymonitor/volatility_data.go @@ -1,11 +1,13 @@ package volatilitymonitor import ( + "sync" "time" ) type volatilityData struct { - log []int64 + lock sync.Mutex + log []int64 } /** @@ -13,6 +15,8 @@ type volatilityData struct { * If not it'll append on the end. */ func (bd *volatilityData) Add(expiry time.Duration) { + bd.lock.Lock() + defer bd.lock.Unlock() n := time.Now().UnixNano() for i := 0; i < len(bd.log); i++ { if bd.log[i] < n-int64(expiry) { @@ -24,6 +28,8 @@ func (bd *volatilityData) Add(expiry time.Duration) { } func (bd *volatilityData) Count(expiry time.Duration) int { + bd.lock.Lock() + defer bd.lock.Unlock() if len(bd.log) == 0 { return 0 // Special case this } @@ -38,6 +44,8 @@ func (bd *volatilityData) Count(expiry time.Duration) int { } func (bd *volatilityData) Clean(expiry time.Duration) { + bd.lock.Lock() + defer bd.lock.Unlock() n := time.Now().UnixNano() newlog := make([]int64, 0) for i := 0; i < len(bd.log); i++ { diff --git a/pkg/storage/volatilitymonitor/volatility_monitor.go b/pkg/storage/volatilitymonitor/volatility_monitor.go index 14f3976..11acd1b 100644 --- a/pkg/storage/volatilitymonitor/volatility_monitor.go +++ b/pkg/storage/volatilitymonitor/volatility_monitor.go @@ -116,17 +116,16 @@ func (i *VolatilityMonitor) Remove(block int) { func (i *VolatilityMonitor) GetVolatility(block int) int { i.blockDataLock.Lock() - defer i.blockDataLock.Unlock() bd, ok := i.blockData[uint(block)] if ok { + i.blockDataLock.Unlock() return bd.Count(i.expiry) } + i.blockDataLock.Unlock() return 0 } func (i *VolatilityMonitor) GetTotalVolatility() int { - i.blockDataLock.Lock() - defer i.blockDataLock.Unlock() return i.totalData.Count(i.expiry) } @@ -156,8 +155,9 @@ func (i *VolatilityMonitor) WriteAt(buffer []byte, offset int64) (int, error) { bd = &volatilityData{log: make([]int64, 0)} i.blockData[block] = bd } - bd.Add(i.expiry) i.blockDataLock.Unlock() + + bd.Add(i.expiry) } // Always update the total i.totalData.Add(i.expiry) // Add to the total volatility counter