1 /*
2  * Copyright 2019 The Netty Project
3  *
4  * The Netty Project licenses this file to you under the Apache License,
5  * version 2.0 (the "License"); you may not use this file except in compliance
6  * with the License. You may obtain a copy of the License at:
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations
14  * under the License.
15  */

16 package io.netty.util.internal;
17
18 import static io.netty.util.internal.ObjectUtil.checkPositive;
19
20 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
21
22 import io.netty.util.IllegalReferenceCountException;
23 import io.netty.util.ReferenceCounted;
24
25 /**
26  * Common logic for {@link ReferenceCounted} implementations
27  */

28 public abstract class ReferenceCountUpdater<T extends ReferenceCounted> {
29     /*
30      * Implementation notes:
31      *
32      * For the updated int field:
33      *   Even => "real" refcount is (refCnt >>> 1)
34      *   Odd  => "real" refcount is 0
35      *
36      * (x & y) appears to be surprisingly expensive relative to (x == y). Thus this class uses
37      * a fast-path in some places for most common low values when checking for live (even) refcounts,
38      * for example: if (rawCnt == 2 || rawCnt == 4 || (rawCnt & 1) == 0) { ...
39      */

40
41     protected ReferenceCountUpdater() { }
42
43     public static long getUnsafeOffset(Class<? extends ReferenceCounted> clz, String fieldName) {
44         try {
45             if (PlatformDependent.hasUnsafe()) {
46                 return PlatformDependent.objectFieldOffset(clz.getDeclaredField(fieldName));
47             }
48         } catch (Throwable ignore) {
49             // fall-back
50         }
51         return -1;
52     }
53
54     protected abstract AtomicIntegerFieldUpdater<T> updater();
55
56     protected abstract long unsafeOffset();
57
58     public final int initialValue() {
59         return 2;
60     }
61
62     private static int realRefCnt(int rawCnt) {
63         return rawCnt != 2 && rawCnt != 4 && (rawCnt & 1) != 0 ? 0 : rawCnt >>> 1;
64     }
65
66     /**
67      * Like {@link #realRefCnt(int)} but throws if refCnt == 0
68      */

69     private static int toLiveRealRefCnt(int rawCnt, int decrement) {
70         if (rawCnt == 2 || rawCnt == 4 || (rawCnt & 1) == 0) {
71             return rawCnt >>> 1;
72         }
73         // odd rawCnt => already deallocated
74         throw new IllegalReferenceCountException(0, -decrement);
75     }
76
77     private int nonVolatileRawCnt(T instance) {
78         // TODO: Once we compile against later versions of Java we can replace the Unsafe usage here by varhandles.
79         final long offset = unsafeOffset();
80         return offset != -1 ? PlatformDependent.getInt(instance, offset) : updater().get(instance);
81     }
82
83     public final int refCnt(T instance) {
84         return realRefCnt(updater().get(instance));
85     }
86
87     public final boolean isLiveNonVolatile(T instance) {
88         final long offset = unsafeOffset();
89         final int rawCnt = offset != -1 ? PlatformDependent.getInt(instance, offset) : updater().get(instance);
90
91         // The "real" ref count is > 0 if the rawCnt is even.
92         return rawCnt == 2 || rawCnt == 4 || rawCnt == 6 || rawCnt == 8 || (rawCnt & 1) == 0;
93     }
94
95     /**
96      * An unsafe operation that sets the reference count directly
97      */

98     public final void setRefCnt(T instance, int refCnt) {
99         updater().set(instance, refCnt > 0 ? refCnt << 1 : 1); // overflow OK here
100     }
101
102     /**
103      * Resets the reference count to 1
104      */

105     public final void resetRefCnt(T instance) {
106         updater().set(instance, initialValue());
107     }
108
109     public final T retain(T instance) {
110         return retain0(instance, 1, 2);
111     }
112
113     public final T retain(T instance, int increment) {
114         // all changes to the raw count are 2x the "real" change - overflow is OK
115         int rawIncrement = checkPositive(increment, "increment") << 1;
116         return retain0(instance, increment, rawIncrement);
117     }
118
119     // rawIncrement == increment << 1
120     private T retain0(T instance, final int increment, final int rawIncrement) {
121         int oldRef = updater().getAndAdd(instance, rawIncrement);
122         if (oldRef != 2 && oldRef != 4 && (oldRef & 1) != 0) {
123             throw new IllegalReferenceCountException(0, increment);
124         }
125         // don't pass 0!
126         if ((oldRef <= 0 && oldRef + rawIncrement >= 0)
127                 || (oldRef >= 0 && oldRef + rawIncrement < oldRef)) {
128             // overflow case
129             updater().getAndAdd(instance, -rawIncrement);
130             throw new IllegalReferenceCountException(realRefCnt(oldRef), increment);
131         }
132         return instance;
133     }
134
135     public final boolean release(T instance) {
136         int rawCnt = nonVolatileRawCnt(instance);
137         return rawCnt == 2 ? tryFinalRelease0(instance, 2) || retryRelease0(instance, 1)
138                 : nonFinalRelease0(instance, 1, rawCnt, toLiveRealRefCnt(rawCnt, 1));
139     }
140
141     public final boolean release(T instance, int decrement) {
142         int rawCnt = nonVolatileRawCnt(instance);
143         int realCnt = toLiveRealRefCnt(rawCnt, checkPositive(decrement, "decrement"));
144         return decrement == realCnt ? tryFinalRelease0(instance, rawCnt) || retryRelease0(instance, decrement)
145                 : nonFinalRelease0(instance, decrement, rawCnt, realCnt);
146     }
147
148     private boolean tryFinalRelease0(T instance, int expectRawCnt) {
149         return updater().compareAndSet(instance, expectRawCnt, 1); // any odd number will work
150     }
151
152     private boolean nonFinalRelease0(T instance, int decrement, int rawCnt, int realCnt) {
153         if (decrement < realCnt
154                 // all changes to the raw count are 2x the "real" change - overflow is OK
155                 && updater().compareAndSet(instance, rawCnt, rawCnt - (decrement << 1))) {
156             return false;
157         }
158         return retryRelease0(instance, decrement);
159     }
160
161     private boolean retryRelease0(T instance, int decrement) {
162         for (;;) {
163             int rawCnt = updater().get(instance), realCnt = toLiveRealRefCnt(rawCnt, decrement);
164             if (decrement == realCnt) {
165                 if (tryFinalRelease0(instance, rawCnt)) {
166                     return true;
167                 }
168             } else if (decrement < realCnt) {
169                 // all changes to the raw count are 2x the "real" change
170                 if (updater().compareAndSet(instance, rawCnt, rawCnt - (decrement << 1))) {
171                     return false;
172                 }
173             } else {
174                 throw new IllegalReferenceCountException(realCnt, -decrement);
175             }
176             Thread.yield(); // this benefits throughput under high contention
177         }
178     }
179 }
180