1 /*
2  * Copyright (C) 2013 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.*;
18 import java.lang.Runtime;
19 
20 public class Main {
21     static Object nativeLock = new Object();
22     static int nativeBytes = 0;
23     static Object runtime;
24     static Method register_native_allocation;
25     static Method register_native_free;
26     static long maxMem = 0;
27 
28     static class NativeAllocation {
29         private int bytes;
30 
NativeAllocation(int bytes)31         NativeAllocation(int bytes) throws Exception {
32             this.bytes = bytes;
33             register_native_allocation.invoke(runtime, bytes);
34             synchronized (nativeLock) {
35                 nativeBytes += bytes;
36                 if (nativeBytes > maxMem) {
37                     throw new OutOfMemoryError();
38                 }
39             }
40         }
41 
finalize()42         protected void finalize() throws Exception {
43             synchronized (nativeLock) {
44                 nativeBytes -= bytes;
45             }
46             register_native_free.invoke(runtime, bytes);
47         }
48     }
49 
main(String[] args)50     public static void main(String[] args) throws Exception {
51         Class<?> vm_runtime = Class.forName("dalvik.system.VMRuntime");
52         Method get_runtime = vm_runtime.getDeclaredMethod("getRuntime");
53         runtime = get_runtime.invoke(null);
54         register_native_allocation = vm_runtime.getDeclaredMethod("registerNativeAllocation", Integer.TYPE);
55         register_native_free = vm_runtime.getDeclaredMethod("registerNativeFree", Integer.TYPE);
56         maxMem = Runtime.getRuntime().maxMemory();
57         int count = 16;
58         int size = (int)(maxMem / 2 / count);
59         int allocation_count = 256;
60         NativeAllocation[] allocations = new NativeAllocation[count];
61         for (int i = 0; i < allocation_count; ++i) {
62             allocations[i % count] = new NativeAllocation(size);
63         }
64         System.out.println("Test complete");
65     }
66 }
67 
68