1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * 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, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.car.apps.common; 17 18 /** 19 * @hide 20 */ 21 public class RefcountObject<T> { 22 23 public interface RefcountListener { onRefcountZero(RefcountObject<?> object)24 void onRefcountZero(RefcountObject<?> object); 25 } 26 27 private RefcountObject.RefcountListener mRefcountListener; 28 private int mRefcount; 29 private T mObject; 30 RefcountObject(T object)31 public RefcountObject(T object) { 32 mObject = object; 33 } 34 setRefcountListener(RefcountObject.RefcountListener listener)35 public void setRefcountListener(RefcountObject.RefcountListener listener) { 36 mRefcountListener = listener; 37 } 38 addRef()39 public synchronized int addRef() { 40 mRefcount++; 41 return mRefcount; 42 } 43 releaseRef()44 public synchronized int releaseRef() { 45 mRefcount--; 46 if (mRefcount == 0 && mRefcountListener != null) { 47 mRefcountListener.onRefcountZero(this); 48 } 49 return mRefcount; 50 } 51 getRef()52 public synchronized int getRef() { 53 return mRefcount; 54 } 55 getObject()56 public T getObject() { 57 return mObject; 58 } 59 } 60