Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Acquire read lock instead of exclusive lock for langBaseCache. #4279

Merged
merged 3 commits into from
Nov 19, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions tok/langbase.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const enBase = "en"

// langBaseCache keeps a copy of lang -> base conversions.
var langBaseCache struct {
sync.Mutex
sync.RWMutex
m map[string]string
}

Expand All @@ -38,15 +38,26 @@ func langBase(lang string) string {
if lang == "" {
return enBase // default to this
}

// Acquire the read lock and lookup for the lang in cache.
langBaseCache.RLock()

// check if we already have this
if s, found := langBaseCache.m[lang]; found {
langBaseCache.RUnlock()
return s
}

// Upgrade the lock only since the lang is not found in cache.
langBaseCache.RUnlock()
langBaseCache.Lock()
defer langBaseCache.Unlock()
if langBaseCache.m == nil {
langBaseCache.m = make(map[string]string)
}
// check if we already have this

// Recheck if the lang is added to the cache.
if s, found := langBaseCache.m[lang]; found {
return s
}

// Parse will return the best guess for a language tag.
// It will return undefined, or 'language.Und', if it gives up. That means the language
// tag is either new (to the standard) or simply invalid.
Expand All @@ -71,3 +82,7 @@ func langBase(lang string) string {
langBaseCache.m[lang] = enBase
return enBase
}

func init() {
langBaseCache.m = make(map[string]string)
}