-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemoizableFutureTask.go
More file actions
67 lines (50 loc) · 1.05 KB
/
memoizableFutureTask.go
File metadata and controls
67 lines (50 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package executor
import (
"hash/fnv"
"sync"
)
var mutex sync.Mutex
type MemoizableFutureTask[V any] struct {
taskItem Task[V]
cache *sync.Map
}
func NewMemoizableFutureTask[V any](t Task[V], cache *sync.Map) Task[V] {
return &MemoizableFutureTask[V]{
taskItem: t,
cache: cache,
}
}
// Exec godoc
func (m *MemoizableFutureTask[V]) Exec() (V, error) {
hashVal := getHash(m.Hash(hashStr))
result, ok := m.cache.Load(hashVal)
if !ok {
mutex.Lock()
result, ok = m.cache.Load(hashVal)
if !ok {
ft := NewFutureTask(m.taskItem)
m.cache.Store(hashVal, ft)
result = ft
}
mutex.Unlock()
}
return result.(*FutureTask[V]).Get()
}
// Hash godoc
// is used for memoization
// generate it using input parameters
func (m *MemoizableFutureTask[V]) Hash(hashStr func(string) int) []int {
return m.taskItem.Hash(hashStr)
}
func hashStr(s string) int {
h := fnv.New32a()
h.Write([]byte(s))
return int(h.Sum32())
}
func getHash(is []int) int {
ourhashes := 5
for _, h := range is {
ourhashes = 21*ourhashes + h
}
return ourhashes
}