View Javadoc
1   /*
2    * Copyright 2013 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;
17  
18  import io.netty.util.internal.RefCnt;
19  
20  /**
21   * Abstract base class for classes wants to implement {@link ReferenceCounted}.
22   */
23  public abstract class AbstractReferenceCounted implements ReferenceCounted {
24  
25      private final RefCnt refCnt = new RefCnt();
26  
27      @Override
28      public int refCnt() {
29          return RefCnt.refCnt(refCnt);
30      }
31  
32      /**
33       * An unsafe operation intended for use by a subclass that sets the reference count of the object directly
34       */
35      protected void setRefCnt(int refCnt) {
36          RefCnt.setRefCnt(this.refCnt, refCnt);
37      }
38  
39      @Override
40      public ReferenceCounted retain() {
41          RefCnt.retain(refCnt);
42          return this;
43      }
44  
45      @Override
46      public ReferenceCounted retain(int increment) {
47          RefCnt.retain(refCnt, increment);
48          return this;
49      }
50  
51      @Override
52      public ReferenceCounted touch() {
53          return touch(null);
54      }
55  
56      @Override
57      public boolean release() {
58          return handleRelease(RefCnt.release(refCnt));
59      }
60  
61      @Override
62      public boolean release(int decrement) {
63          return handleRelease(RefCnt.release(refCnt, decrement));
64      }
65  
66      private boolean handleRelease(boolean result) {
67          if (result) {
68              deallocate();
69          }
70          return result;
71      }
72  
73      /**
74       * Called once {@link #refCnt()} is equals 0.
75       */
76      protected abstract void deallocate();
77  }