sharedobject.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. ******************************************************************************
  5. * Copyright (C) 2015, International Business Machines
  6. * Corporation and others. All Rights Reserved.
  7. ******************************************************************************
  8. * sharedobject.cpp
  9. */
  10. #include "sharedobject.h"
  11. #include "mutex.h"
  12. #include "uassert.h"
  13. #include "umutex.h"
  14. #include "unifiedcache.h"
  15. U_NAMESPACE_BEGIN
  16. SharedObject::~SharedObject() {}
  17. UnifiedCacheBase::~UnifiedCacheBase() {}
  18. void
  19. SharedObject::addRef() const {
  20. umtx_atomic_inc(&hardRefCount);
  21. }
  22. // removeRef Decrement the reference count and delete if it is zero.
  23. // Note that SharedObjects with a non-null cachePtr are owned by the
  24. // unified cache, and the cache will be responsible for the actual deletion.
  25. // The deletion could be as soon as immediately following the
  26. // update to the reference count, if another thread is running
  27. // a cache eviction cycle concurrently.
  28. // NO ACCESS TO *this PERMITTED AFTER REFERENCE COUNT == 0 for cached objects.
  29. // THE OBJECT MAY ALREADY BE GONE.
  30. void
  31. SharedObject::removeRef() const {
  32. const UnifiedCacheBase *cache = this->cachePtr;
  33. int32_t updatedRefCount = umtx_atomic_dec(&hardRefCount);
  34. U_ASSERT(updatedRefCount >= 0);
  35. if (updatedRefCount == 0) {
  36. if (cache) {
  37. cache->handleUnreferencedObject();
  38. } else {
  39. delete this;
  40. }
  41. }
  42. }
  43. int32_t
  44. SharedObject::getRefCount() const {
  45. return umtx_loadAcquire(hardRefCount);
  46. }
  47. void
  48. SharedObject::deleteIfZeroRefCount() const {
  49. if (this->cachePtr == nullptr && getRefCount() == 0) {
  50. delete this;
  51. }
  52. }
  53. U_NAMESPACE_END