Reduce lock contention

This commit is contained in:
Frank Denis 2019-10-21 18:36:47 +02:00
parent 70970d2333
commit ffd60d21db
1 changed files with 7 additions and 4 deletions

View File

@ -84,7 +84,6 @@ func ParseIP(ipStr string) net.IP {
// If ttl < 0, never expire // If ttl < 0, never expire
// Otherwise, ttl is set to max(ttl, xTransport.timeout) // Otherwise, ttl is set to max(ttl, xTransport.timeout)
func (xTransport *XTransport) saveCachedIP(host string, ip net.IP, ttl time.Duration) { func (xTransport *XTransport) saveCachedIP(host string, ip net.IP, ttl time.Duration) {
xTransport.cachedIPs.Lock()
item := &CachedIPItem{ip: ip, ttl: time.Time{}} item := &CachedIPItem{ip: ip, ttl: time.Time{}}
if ttl >= 0 { if ttl >= 0 {
if ttl < xTransport.timeout { if ttl < xTransport.timeout {
@ -92,19 +91,23 @@ func (xTransport *XTransport) saveCachedIP(host string, ip net.IP, ttl time.Dura
} }
item.ttl = time.Now().Add(ttl) item.ttl = time.Now().Add(ttl)
} }
xTransport.cachedIPs.Lock()
xTransport.cachedIPs.cache[host] = item xTransport.cachedIPs.cache[host] = item
xTransport.cachedIPs.Unlock() xTransport.cachedIPs.Unlock()
} }
func (xTransport *XTransport) loadCachedIP(host string, deleteIfExpired bool) (net.IP, bool) { func (xTransport *XTransport) loadCachedIP(host string, deleteIfExpired bool) (net.IP, bool) {
xTransport.cachedIPs.Lock() xTransport.cachedIPs.RLock()
defer xTransport.cachedIPs.Unlock()
item, ok := xTransport.cachedIPs.cache[host] item, ok := xTransport.cachedIPs.cache[host]
xTransport.cachedIPs.RUnlock()
if !ok { if !ok {
return nil, false return nil, false
} }
if deleteIfExpired && !item.ttl.IsZero() && time.Until(item.ttl) < 0 { ttl := item.ttl
if deleteIfExpired && !ttl.IsZero() && time.Until(ttl) < 0 {
xTransport.cachedIPs.Lock()
delete(xTransport.cachedIPs.cache, host) delete(xTransport.cachedIPs.cache, host)
xTransport.cachedIPs.Unlock()
return nil, false return nil, false
} }
return item.ip, ok return item.ip, ok