1 /*
2 
3  * Copyright (C) 2016 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 import java.lang.reflect.Method;
19 import java.util.Map;
20 
21 import dalvik.system.VMDebug;
22 
23 public class Main implements Runnable {
24     static final int numberOfThreads = 4;
25     static final int totalOperations = 1000;
26     static final int maxStackDepth = 128;
27     static Method enableAllocTrackingMethod;
28     static Object holder;
29     static volatile boolean trackingThreadDone = false;
30     int threadIndex;
31 
Main(int index)32     Main(int index) {
33         threadIndex = index;
34     }
35 
main(String[] args)36     public static void main(String[] args) throws Exception {
37       Class<?> klass = Class.forName("org.apache.harmony.dalvik.ddmc.DdmVmInternal");
38       if (klass == null) {
39           throw new AssertionError("Couldn't find DdmVmInternal class");
40       }
41       enableAllocTrackingMethod = klass.getDeclaredMethod("enableRecentAllocations",
42               Boolean.TYPE);
43       if (enableAllocTrackingMethod == null) {
44           throw new AssertionError("Couldn't find enableRecentAllocations method");
45       }
46 
47       final Thread[] threads = new Thread[numberOfThreads];
48       for (int t = 0; t < threads.length; t++) {
49           threads[t] = new Thread(new Main(t));
50           threads[t].start();
51       }
52       for (Thread t : threads) {
53           t.join();
54       }
55       System.out.println("Finishing");
56     }
57 
run()58     public void run() {
59         if (threadIndex == 0) {
60             for (int i = 0; i < totalOperations; ++i) {
61                 try {
62                     VMDebug.setAllocTrackerStackDepth(i % (maxStackDepth + 1));
63                     enableAllocTrackingMethod.invoke(null, true);
64                     holder = new Object();
65                     enableAllocTrackingMethod.invoke(null, false);
66                 } catch (Exception e) {
67                     System.out.println(e);
68                     return;
69                 }
70             }
71             trackingThreadDone = true;
72         } else {
73             while (!trackingThreadDone) {
74                 holder = new Object();
75             }
76         }
77     }
78 }
79