View Javadoc
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    *   https://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      public void setInitialValue(T instance) {
63          final long offset = unsafeOffset();
64          if (offset == -1) {
65              updater().set(instance, initialValue());
66          } else {
67              PlatformDependent.safeConstructPutInt(instance, offset, initialValue());
68          }
69      }
70  
71      private static int realRefCnt(int rawCnt) {
72          return rawCnt != 2 && rawCnt != 4 && (rawCnt & 1) != 0 ? 0 : rawCnt >>> 1;
73      }
74  
75      /**
76       * Like {@link #realRefCnt(int)} but throws if refCnt == 0
77       */
78      private static int toLiveRealRefCnt(int rawCnt, int decrement) {
79          if (rawCnt == 2 || rawCnt == 4 || (rawCnt & 1) == 0) {
80              return rawCnt >>> 1;
81          }
82          // odd rawCnt => already deallocated
83          throw new IllegalReferenceCountException(0, -decrement);
84      }
85  
86      private int nonVolatileRawCnt(T instance) {
87          // TODO: Once we compile against later versions of Java we can replace the Unsafe usage here by varhandles.
88          final long offset = unsafeOffset();
89          return offset != -1 ? PlatformDependent.getInt(instance, offset) : updater().get(instance);
90      }
91  
92      public final int refCnt(T instance) {
93          return realRefCnt(updater().get(instance));
94      }
95  
96      public final boolean isLiveNonVolatile(T instance) {
97          final long offset = unsafeOffset();
98          final int rawCnt = offset != -1 ? PlatformDependent.getInt(instance, offset) : updater().get(instance);
99  
100         // The "real" ref count is > 0 if the rawCnt is even.
101         return rawCnt == 2 || rawCnt == 4 || rawCnt == 6 || rawCnt == 8 || (rawCnt & 1) == 0;
102     }
103 
104     /**
105      * An unsafe operation that sets the reference count directly
106      */
107     public final void setRefCnt(T instance, int refCnt) {
108         updater().set(instance, refCnt > 0 ? refCnt << 1 : 1); // overflow OK here
109     }
110 
111     /**
112      * Resets the reference count to 1
113      */
114     public final void resetRefCnt(T instance) {
115         updater().set(instance, initialValue());
116     }
117 
118     public final T retain(T instance) {
119         return retain0(instance, 1, 2);
120     }
121 
122     public final T retain(T instance, int increment) {
123         // all changes to the raw count are 2x the "real" change - overflow is OK
124         int rawIncrement = checkPositive(increment, "increment") << 1;
125         return retain0(instance, increment, rawIncrement);
126     }
127 
128     // rawIncrement == increment << 1
129     private T retain0(T instance, final int increment, final int rawIncrement) {
130         int oldRef = updater().getAndAdd(instance, rawIncrement);
131         if (oldRef != 2 && oldRef != 4 && (oldRef & 1) != 0) {
132             throw new IllegalReferenceCountException(0, increment);
133         }
134         // don't pass 0!
135         if ((oldRef <= 0 && oldRef + rawIncrement >= 0)
136                 || (oldRef >= 0 && oldRef + rawIncrement < oldRef)) {
137             // overflow case
138             updater().getAndAdd(instance, -rawIncrement);
139             throw new IllegalReferenceCountException(realRefCnt(oldRef), increment);
140         }
141         return instance;
142     }
143 
144     public final boolean release(T instance) {
145         int rawCnt = nonVolatileRawCnt(instance);
146         return rawCnt == 2 ? tryFinalRelease0(instance, 2) || retryRelease0(instance, 1)
147                 : nonFinalRelease0(instance, 1, rawCnt, toLiveRealRefCnt(rawCnt, 1));
148     }
149 
150     public final boolean release(T instance, int decrement) {
151         int rawCnt = nonVolatileRawCnt(instance);
152         int realCnt = toLiveRealRefCnt(rawCnt, checkPositive(decrement, "decrement"));
153         return decrement == realCnt ? tryFinalRelease0(instance, rawCnt) || retryRelease0(instance, decrement)
154                 : nonFinalRelease0(instance, decrement, rawCnt, realCnt);
155     }
156 
157     private boolean tryFinalRelease0(T instance, int expectRawCnt) {
158         return updater().compareAndSet(instance, expectRawCnt, 1); // any odd number will work
159     }
160 
161     private boolean nonFinalRelease0(T instance, int decrement, int rawCnt, int realCnt) {
162         if (decrement < realCnt
163                 // all changes to the raw count are 2x the "real" change - overflow is OK
164                 && updater().compareAndSet(instance, rawCnt, rawCnt - (decrement << 1))) {
165             return false;
166         }
167         return retryRelease0(instance, decrement);
168     }
169 
170     private boolean retryRelease0(T instance, int decrement) {
171         for (;;) {
172             int rawCnt = updater().get(instance), realCnt = toLiveRealRefCnt(rawCnt, decrement);
173             if (decrement == realCnt) {
174                 if (tryFinalRelease0(instance, rawCnt)) {
175                     return true;
176                 }
177             } else if (decrement < realCnt) {
178                 // all changes to the raw count are 2x the "real" change
179                 if (updater().compareAndSet(instance, rawCnt, rawCnt - (decrement << 1))) {
180                     return false;
181                 }
182             } else {
183                 throw new IllegalReferenceCountException(realCnt, -decrement);
184             }
185             Thread.yield(); // this benefits throughput under high contention
186         }
187     }
188 }