1 /* 2 * Copyright (C) 2019 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 // DeadReferenceSafeTest, but with a reachabilityFence. 18 19 import dalvik.annotation.optimization.DeadReferenceSafe; 20 import java.lang.ref.Reference; 21 import java.util.concurrent.atomic.AtomicInteger; 22 23 @DeadReferenceSafe 24 public final class ReachabilityFenceTest { 25 static AtomicInteger nFinalized = new AtomicInteger(0); 26 private static final int INNER_ITERS = 10; 27 static int count; 28 int n = 1; 29 $noinline$loop()30 private static void $noinline$loop() { 31 ReachabilityFenceTest x; 32 // Each loop allocates INNER_ITERS ReachabilitySenstiveTest objects. 33 for (int i = 0; i < INNER_ITERS; ++i) { 34 // We've allocated i objects so far. 35 x = new ReachabilityFenceTest(); 36 count += x.n; 37 // x is dead here. 38 if (i == 5) { 39 // The rechabilityFence should keep the last allocated object reachable. 40 // Thus the last instance should not be finalized. 41 Main.$noinline$gcAndCheck(nFinalized, 5, "ReachabilityFence", 42 "reachabilityFence failed to keep object live."); 43 } 44 Reference.reachabilityFence(x); 45 } 46 } 47 reset(int expected_count)48 private static void reset(int expected_count) { 49 Runtime.getRuntime().gc(); 50 System.runFinalization(); 51 if (nFinalized.get() != expected_count) { 52 System.out.println("ReachabilityFenceTest: Wrong number of finalized objects:" 53 + nFinalized.get()); 54 } 55 nFinalized.set(0); 56 } 57 finalize()58 protected void finalize() { 59 nFinalized.incrementAndGet(); 60 } 61 runTest()62 public static void runTest() { 63 try { 64 Main.ensureCompiled(ReachabilityFenceTest.class, "$noinline$loop"); 65 } catch (NoSuchMethodException e) { 66 System.out.println("Unexpectedly threw " + e); 67 } 68 69 $noinline$loop(); 70 71 if (count != INNER_ITERS) { 72 System.out.println("ReachabilityFenceTest: Final count wrong: " + count); 73 } 74 reset(INNER_ITERS); 75 } 76 } 77