1 /* 2 * Copyright (C) 2014 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 17 package com.android.internal.util; 18 19 /** 20 * Helper class that contains a strong reference to a VirtualRefBase native 21 * object. This will incStrong in the ctor, and decStrong in the finalizer. 22 * It currently does no accounting of natively allocated memory, for the 23 * benefit of either GC triggering or heap profiling. 24 */ 25 public final class VirtualRefBasePtr { 26 // TODO(b/231729094): Convert to NativeAllocationRegistry? 27 private long mNativePtr; 28 VirtualRefBasePtr(long ptr)29 public VirtualRefBasePtr(long ptr) { 30 mNativePtr = ptr; 31 nIncStrong(mNativePtr); 32 } 33 34 /* 35 * Return the RefBase / VirtualLightRefBase native pointer. Warning: The 36 * caller must ensure that the VirtualRefBasePtr object remains reachable 37 * while the result is in use. Ideally, the caller should invoke 38 * {@link java.lang.ref.Reference#reachabilityFence} 39 * on the VirtualRefBasePtr object (or on an object that refers to it) as 40 * soon as the result is no longer needed. 41 */ get()42 public long get() { 43 return mNativePtr; 44 } 45 release()46 public void release() { 47 if (mNativePtr != 0) { 48 nDecStrong(mNativePtr); 49 mNativePtr = 0; 50 } 51 } 52 53 @Override finalize()54 protected void finalize() throws Throwable { 55 try { 56 release(); 57 } finally { 58 super.finalize(); 59 } 60 } 61 nIncStrong(long ptr)62 private static native void nIncStrong(long ptr); nDecStrong(long ptr)63 private static native void nDecStrong(long ptr); 64 } 65