github.com/TeaOSLab/EdgeNode@v1.3.8/internal/ttlcache/manager.go (about)

     1  // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package ttlcache
     4  
     5  import (
     6  	"github.com/TeaOSLab/EdgeNode/internal/goman"
     7  	"github.com/TeaOSLab/EdgeNode/internal/zero"
     8  	"sync"
     9  	"time"
    10  )
    11  
    12  var SharedManager = NewManager()
    13  
    14  type GCAble interface {
    15  	GC()
    16  }
    17  
    18  type Manager struct {
    19  	ticker *time.Ticker
    20  	locker sync.Mutex
    21  
    22  	cacheMap map[GCAble]zero.Zero
    23  }
    24  
    25  func NewManager() *Manager {
    26  	var manager = &Manager{
    27  		ticker:   time.NewTicker(2 * time.Second),
    28  		cacheMap: map[GCAble]zero.Zero{},
    29  	}
    30  
    31  	goman.New(func() {
    32  		manager.init()
    33  	})
    34  
    35  	return manager
    36  }
    37  
    38  func (this *Manager) init() {
    39  	for range this.ticker.C {
    40  		this.locker.Lock()
    41  		for cache := range this.cacheMap {
    42  			cache.GC()
    43  		}
    44  		this.locker.Unlock()
    45  	}
    46  }
    47  
    48  func (this *Manager) Add(cache GCAble) {
    49  	this.locker.Lock()
    50  	this.cacheMap[cache] = zero.New()
    51  	this.locker.Unlock()
    52  }
    53  
    54  func (this *Manager) Remove(cache GCAble) {
    55  	this.locker.Lock()
    56  	delete(this.cacheMap, cache)
    57  	this.locker.Unlock()
    58  }
    59  
    60  func (this *Manager) Count() int {
    61  	this.locker.Lock()
    62  	defer this.locker.Unlock()
    63  	return len(this.cacheMap)
    64  }