Skip to content

Commit

Permalink
race in vm fix
Browse files Browse the repository at this point in the history
Signed-off-by: Jimmy Moore <[email protected]>
  • Loading branch information
jimmyaxod committed Nov 27, 2024
1 parent 2a0bd60 commit b09ac7a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
10 changes: 9 additions & 1 deletion pkg/storage/volatilitymonitor/volatility_data.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
package volatilitymonitor

import (
"sync"
"time"
)

type volatilityData struct {
log []int64
lock sync.Mutex
log []int64
}

/**
* Add will do a lazy add - if it can find one that has expired it'll replace it and return.
* 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) {
Expand All @@ -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
}
Expand All @@ -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++ {
Expand Down
8 changes: 4 additions & 4 deletions pkg/storage/volatilitymonitor/volatility_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit b09ac7a

Please sign in to comment.