cache.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright (c) 2016 Couchbase, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package registry
  15. import (
  16. "fmt"
  17. "sync"
  18. )
  19. var ErrAlreadyDefined = fmt.Errorf("item already defined")
  20. type CacheBuild func(name string, config map[string]interface{}, cache *Cache) (interface{}, error)
  21. type ConcurrentCache struct {
  22. mutex sync.RWMutex
  23. data map[string]interface{}
  24. }
  25. func NewConcurrentCache() *ConcurrentCache {
  26. return &ConcurrentCache{
  27. data: make(map[string]interface{}),
  28. }
  29. }
  30. func (c *ConcurrentCache) ItemNamed(name string, cache *Cache, build CacheBuild) (interface{}, error) {
  31. c.mutex.RLock()
  32. item, cached := c.data[name]
  33. if cached {
  34. c.mutex.RUnlock()
  35. return item, nil
  36. }
  37. // give up read lock
  38. c.mutex.RUnlock()
  39. // try to build it
  40. newItem, err := build(name, nil, cache)
  41. if err != nil {
  42. return nil, err
  43. }
  44. // acquire write lock
  45. c.mutex.Lock()
  46. defer c.mutex.Unlock()
  47. // check again because it could have been created while trading locks
  48. item, cached = c.data[name]
  49. if cached {
  50. return item, nil
  51. }
  52. c.data[name] = newItem
  53. return newItem, nil
  54. }
  55. func (c *ConcurrentCache) DefineItem(name string, typ string, config map[string]interface{}, cache *Cache, build CacheBuild) (interface{}, error) {
  56. c.mutex.RLock()
  57. _, cached := c.data[name]
  58. if cached {
  59. c.mutex.RUnlock()
  60. return nil, ErrAlreadyDefined
  61. }
  62. // give up read lock so others lookups can proceed
  63. c.mutex.RUnlock()
  64. // really not there, try to build it
  65. newItem, err := build(typ, config, cache)
  66. if err != nil {
  67. return nil, err
  68. }
  69. // now we've built it, acquire lock
  70. c.mutex.Lock()
  71. defer c.mutex.Unlock()
  72. // check again because it could have been created while trading locks
  73. _, cached = c.data[name]
  74. if cached {
  75. return nil, ErrAlreadyDefined
  76. }
  77. c.data[name] = newItem
  78. return newItem, nil
  79. }