Skip to content

Commit

Permalink
#19 add mutex operation for caching
Browse files Browse the repository at this point in the history
  • Loading branch information
zhengchun committed Dec 13, 2019
1 parent d2c82b9 commit d7df91c
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ package htmlquery
import (
"sync"

"github.com/golang/groupcache/lru"

"github.com/antchfx/xpath"
"github.com/golang/groupcache/lru"
)

// DisableSelectorCache will disable caching for the query selector if value is true.
Expand All @@ -16,8 +15,9 @@ var DisableSelectorCache = false
var SelectorCacheMaxEntries = 50

var (
cacheOnce sync.Once
cache *lru.Cache
cacheOnce sync.Once
cache *lru.Cache
cacheMutex sync.RWMutex
)

func getQuery(expr string) (*xpath.Expr, error) {
Expand All @@ -27,9 +27,14 @@ func getQuery(expr string) (*xpath.Expr, error) {
cacheOnce.Do(func() {
cache = lru.New(50)
})
cacheMutex.RLock()
if v, ok := cache.Get(expr); ok {
cacheMutex.RUnlock()
return v.(*xpath.Expr), nil
}
cacheMutex.RUnlock()
cacheMutex.Lock()
defer cacheMutex.Unlock()
v, err := xpath.Compile(expr)
if err != nil {
return nil, err
Expand Down

0 comments on commit d7df91c

Please sign in to comment.