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
17package benchmarks;
18
19import com.google.caliper.Param;
20import java.lang.ref.Reference;
21import java.lang.ref.SoftReference;
22import java.lang.ref.WeakReference;
23import java.lang.reflect.Field;
24
25public class ReferenceGetBenchmark {
26    @Param boolean intrinsicDisabled;
27
28    private Object obj = "str";
29
30    protected void setUp() throws Exception {
31        Field intrinsicDisabledField = Reference.class.getDeclaredField("disableIntrinsic");
32        intrinsicDisabledField.setAccessible(true);
33        intrinsicDisabledField.setBoolean(null, intrinsicDisabled);
34    }
35
36    public void timeSoftReferenceGet(int reps) throws Exception {
37        Reference soft = new SoftReference(obj);
38        for (int i = 0; i < reps; i++) {
39            Object o = soft.get();
40        }
41    }
42
43    public void timeWeakReferenceGet(int reps) throws Exception {
44        Reference weak = new WeakReference(obj);
45        for (int i = 0; i < reps; i++) {
46            Object o = weak.get();
47        }
48    }
49
50    public void timeNonPreservedWeakReferenceGet(int reps) throws Exception {
51        Reference weak = new WeakReference(obj);
52        obj = null;
53        Runtime.getRuntime().gc();
54        for (int i = 0; i < reps; i++) {
55            Object o = weak.get();
56        }
57    }
58}
59