blob: e41e378c19fbceb78490a049c3363a0d0b688e31 [file] [log] [blame]
Andreas Gampecc13b222016-10-10 19:09:09 -07001/*
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
17import java.util.ArrayList;
Andreas Gampee54eee12016-10-20 19:03:58 -070018import java.util.Arrays;
Andreas Gampecc13b222016-10-10 19:09:09 -070019
20public class Main {
21 public static void main(String[] args) throws Exception {
Andreas Gampecc13b222016-10-10 19:09:09 -070022 doTest();
23 }
24
25 public static void doTest() throws Exception {
26 // Use a list to ensure objects must be allocated.
27 ArrayList<Object> l = new ArrayList<>(100);
28
29 setupObjectFreeCallback();
30
31 enableFreeTracking(true);
32 run(l);
33
34 enableFreeTracking(false);
35 run(l);
36 }
37
38 private static void run(ArrayList<Object> l) {
39 allocate(l, 1);
40 l.clear();
41
42 Runtime.getRuntime().gc();
43
Andreas Gampee54eee12016-10-20 19:03:58 -070044 getAndPrintTags();
Andreas Gampecc13b222016-10-10 19:09:09 -070045 System.out.println("---");
46
47 // Note: the reporting will not depend on the heap layout (which could be unstable). Walking
48 // the tag table should give us a stable output order.
49 for (int i = 10; i <= 1000; i *= 10) {
50 allocate(l, i);
51 }
52 l.clear();
53
54 Runtime.getRuntime().gc();
55
Andreas Gampee54eee12016-10-20 19:03:58 -070056 getAndPrintTags();
Andreas Gampecc13b222016-10-10 19:09:09 -070057 System.out.println("---");
58
59 Runtime.getRuntime().gc();
60
Andreas Gampee54eee12016-10-20 19:03:58 -070061 getAndPrintTags();
Andreas Gampecc13b222016-10-10 19:09:09 -070062 System.out.println("---");
63 }
64
65 private static void allocate(ArrayList<Object> l, long tag) {
66 Object obj = new Object();
67 l.add(obj);
68 setTag(obj, tag);
69 }
70
Andreas Gampee54eee12016-10-20 19:03:58 -070071 private static void getAndPrintTags() {
72 long[] freedTags = getCollectedTags();
73 Arrays.sort(freedTags);
74 System.out.println(Arrays.toString(freedTags));
75 }
76
Andreas Gampecc13b222016-10-10 19:09:09 -070077 private static native void setupObjectFreeCallback();
78 private static native void enableFreeTracking(boolean enable);
79 private static native void setTag(Object o, long tag);
Andreas Gampee54eee12016-10-20 19:03:58 -070080 private static native long[] getCollectedTags();
Andreas Gampecc13b222016-10-10 19:09:09 -070081}