]> git.saurik.com Git - apple/icu.git/blob - icuSources/common/sharedobject.cpp
ICU-57132.0.1.tar.gz
[apple/icu.git] / icuSources / common / sharedobject.cpp
1 /*
2 ******************************************************************************
3 * Copyright (C) 2015, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 ******************************************************************************
6 * sharedobject.cpp
7 */
8 #include "sharedobject.h"
9 #include "uassert.h"
10
11 U_NAMESPACE_BEGIN
12
13 SharedObject::~SharedObject() {}
14
15 UnifiedCacheBase::~UnifiedCacheBase() {}
16
17 void
18 SharedObject::addRef(UBool fromWithinCache) const {
19 umtx_atomic_inc(&totalRefCount);
20
21 // Although items in use may not be correct immediately, it
22 // will be correct eventually.
23 if (umtx_atomic_inc(&hardRefCount) == 1 && cachePtr != NULL) {
24 // If this object is cached, and the hardRefCount goes from 0 to 1,
25 // then the increment must happen from within the cache while the
26 // cache global mutex is locked. In this way, we can be rest assured
27 // that data races can't happen if the cache performs some task if
28 // the hardRefCount is zero while the global cache mutex is locked.
29 (void)fromWithinCache; // Suppress unused variable warning in non-debug builds.
30 U_ASSERT(fromWithinCache);
31 cachePtr->incrementItemsInUse();
32 }
33 }
34
35 void
36 SharedObject::removeRef(UBool fromWithinCache) const {
37 UBool decrementItemsInUse = (umtx_atomic_dec(&hardRefCount) == 0);
38 UBool allReferencesGone = (umtx_atomic_dec(&totalRefCount) == 0);
39
40 // Although items in use may not be correct immediately, it
41 // will be correct eventually.
42 if (decrementItemsInUse && cachePtr != NULL) {
43 if (fromWithinCache) {
44 cachePtr->decrementItemsInUse();
45 } else {
46 cachePtr->decrementItemsInUseWithLockingAndEviction();
47 }
48 }
49 if (allReferencesGone) {
50 delete this;
51 }
52 }
53
54 void
55 SharedObject::addSoftRef() const {
56 umtx_atomic_inc(&totalRefCount);
57 ++softRefCount;
58 }
59
60 void
61 SharedObject::removeSoftRef() const {
62 --softRefCount;
63 if (umtx_atomic_dec(&totalRefCount) == 0) {
64 delete this;
65 }
66 }
67
68 int32_t
69 SharedObject::getRefCount() const {
70 return umtx_loadAcquire(totalRefCount);
71 }
72
73 int32_t
74 SharedObject::getHardRefCount() const {
75 return umtx_loadAcquire(hardRefCount);
76 }
77
78 void
79 SharedObject::deleteIfZeroRefCount() const {
80 if(getRefCount() == 0) {
81 delete this;
82 }
83 }
84
85 U_NAMESPACE_END