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 android.libcore; 18 19 import android.perftests.utils.BenchmarkState; 20 import android.perftests.utils.PerfStatusReporter; 21 import android.test.suitebuilder.annotation.LargeTest; 22 23 import androidx.test.runner.AndroidJUnit4; 24 25 import org.junit.Before; 26 import org.junit.Rule; 27 import org.junit.Test; 28 import org.junit.runner.RunWith; 29 30 import java.lang.ref.Reference; 31 import java.lang.ref.SoftReference; 32 import java.lang.ref.WeakReference; 33 import java.lang.reflect.Field; 34 35 @RunWith(AndroidJUnit4.class) 36 @LargeTest 37 public class ReferenceGetPerfTest { 38 @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); 39 40 boolean mIntrinsicDisabled; 41 42 private Object mObj = "str"; 43 44 @Before setUp()45 public void setUp() throws Exception { 46 Field intrinsicDisabledField = Reference.class.getDeclaredField("disableIntrinsic"); 47 intrinsicDisabledField.setAccessible(true); 48 intrinsicDisabledField.setBoolean(null, mIntrinsicDisabled); 49 } 50 51 @Test timeSoftReferenceGet()52 public void timeSoftReferenceGet() throws Exception { 53 Reference soft = new SoftReference(mObj); 54 BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); 55 while (state.keepRunning()) { 56 Object o = soft.get(); 57 } 58 } 59 60 @Test timeWeakReferenceGet()61 public void timeWeakReferenceGet() throws Exception { 62 Reference weak = new WeakReference(mObj); 63 BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); 64 while (state.keepRunning()) { 65 Object o = weak.get(); 66 } 67 } 68 69 @Test timeNonPreservedWeakReferenceGet()70 public void timeNonPreservedWeakReferenceGet() throws Exception { 71 Reference weak = new WeakReference(mObj); 72 mObj = null; 73 Runtime.getRuntime().gc(); 74 BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); 75 while (state.keepRunning()) { 76 Object o = weak.get(); 77 } 78 } 79 } 80