validity_map.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package collect
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/v2ray/v2ray-core/common/serial"
  6. )
  7. type Validity interface {
  8. IsValid() bool
  9. }
  10. type entry struct {
  11. key string
  12. value Validity
  13. }
  14. type ValidityMap struct {
  15. sync.RWMutex
  16. cache map[string]Validity
  17. cleanupIntervalSec int
  18. }
  19. func NewValidityMap(cleanupIntervalSec int) *ValidityMap {
  20. instance := &ValidityMap{
  21. cache: make(map[string]Validity),
  22. cleanupIntervalSec: cleanupIntervalSec,
  23. }
  24. go instance.cleanup()
  25. return instance
  26. }
  27. func (this *ValidityMap) cleanup() {
  28. for range time.Tick(time.Duration(this.cleanupIntervalSec) * time.Second) {
  29. entry2Remove := make([]entry, 0, 128)
  30. this.RLock()
  31. for key, value := range this.cache {
  32. if !value.IsValid() {
  33. entry2Remove = append(entry2Remove, entry{
  34. key: key,
  35. value: value,
  36. })
  37. }
  38. }
  39. this.RUnlock()
  40. for _, entry := range entry2Remove {
  41. if !entry.value.IsValid() {
  42. this.Lock()
  43. delete(this.cache, entry.key)
  44. this.Unlock()
  45. }
  46. }
  47. }
  48. }
  49. func (this *ValidityMap) Set(key serial.String, value Validity) {
  50. this.Lock()
  51. this.cache[key.String()] = value
  52. this.Unlock()
  53. }
  54. func (this *ValidityMap) Get(key serial.String) Validity {
  55. this.RLock()
  56. defer this.RUnlock()
  57. if value, found := this.cache[key.String()]; found {
  58. return value
  59. }
  60. return nil
  61. }