SimpleThreadSafeCache.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #include <functional>
  8. #include <memory>
  9. #include <mutex>
  10. #include <better/optional.h>
  11. #include <folly/container/EvictingCacheMap.h>
  12. namespace facebook {
  13. namespace react {
  14. /*
  15. * Simple thread-safe LRU cache.
  16. */
  17. template <typename KeyT, typename ValueT, int maxSize>
  18. class SimpleThreadSafeCache {
  19. public:
  20. SimpleThreadSafeCache() : map_{maxSize} {}
  21. /*
  22. * Returns a value from the map with a given key.
  23. * If the value wasn't found in the cache, constructs the value using given
  24. * generator function, stores it inside a cache and returns it.
  25. * Can be called from any thread.
  26. */
  27. ValueT get(const KeyT &key, std::function<ValueT(const KeyT &key)> generator)
  28. const {
  29. std::lock_guard<std::mutex> lock(mutex_);
  30. auto iterator = map_.find(key);
  31. if (iterator == map_.end()) {
  32. auto value = generator(key);
  33. map_.set(key, value);
  34. return value;
  35. }
  36. return iterator->second;
  37. }
  38. /*
  39. * Returns a value from the map with a given key.
  40. * If the value wasn't found in the cache, returns empty optional.
  41. * Can be called from any thread.
  42. */
  43. better::optional<ValueT> get(const KeyT &key) const {
  44. std::lock_guard<std::mutex> lock(mutex_);
  45. auto iterator = map_.find(key);
  46. if (iterator == map_.end()) {
  47. return {};
  48. }
  49. return iterator->second;
  50. }
  51. /*
  52. * Sets a key-value pair in the LRU cache.
  53. * Can be called from any thread.
  54. */
  55. void set(const KeyT &key, const ValueT &value) const {
  56. std::lock_guard<std::mutex> lock(mutex_);
  57. map_.set(std::move(key), std::move(value));
  58. }
  59. private:
  60. mutable folly::EvictingCacheMap<KeyT, ValueT> map_;
  61. mutable std::mutex mutex_;
  62. };
  63. } // namespace react
  64. } // namespace facebook