• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 import java.lang.reflect.Method;
18 import java.util.ArrayList;
19 import java.util.List;
20 
21 public class Main {
22 
main(String[] args)23     public static void main(String[] args) throws Exception {
24         // Setup reflection stuff before allocating to prevent OOME caused by allocations from
25         // Class.forName or getDeclaredMethod.
26         // Reflective equivalent of: dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
27         final Class<?> vm_runtime = Class.forName("dalvik.system.VMRuntime");
28         final Method get_runtime = vm_runtime.getDeclaredMethod("getRuntime");
29         final Object runtime = get_runtime.invoke(null);
30         final Method clear_growth_limit = vm_runtime.getDeclaredMethod("clearGrowthLimit");
31 
32         int alloc1 = allocateTillOOME();
33 
34         // Proactively clean up.
35         Runtime.getRuntime().gc();
36 
37         // Expand the heap to the maximum size.
38         clear_growth_limit.invoke(runtime);
39 
40         int alloc2 = allocateTillOOME();
41 
42         if (alloc1 > alloc2) {
43             System.out.println("ERROR: Allocated less memory after growth" +
44                     "limit cleared (" + alloc1 + " MBs > " + alloc2 + " MBs");
45         } else {
46             System.out.println("Test complete");
47         }
48     }
49 
allocateTillOOME()50     private static int allocateTillOOME() {
51       int allocations = 0;
52       List<byte[]> l = new ArrayList<byte[]>();
53       try {
54           while (true) {
55               // Allocate a MB at a time
56               l.add(new byte[1048576]);
57               allocations++;
58           }
59       } catch (OutOfMemoryError e) {
60           // Help clean up.
61           l.clear();
62       }
63       return allocations;
64     }
65 }
66