blob: a99fe92081a74a39e1ac43c340489e9d2fa6c20b [file] [log] [blame]
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001/*
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
17import java.lang.reflect.*;
Mathieu Chartiere03df652014-09-02 17:36:08 -070018import java.lang.Runtime;
Mathieu Chartier987ccff2013-07-08 11:05:21 -070019
Andreas Gampe1c83cbc2014-07-22 18:52:29 -070020public class Main {
Mathieu Chartier987ccff2013-07-08 11:05:21 -070021 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;
Mathieu Chartiere03df652014-09-02 17:36:08 -070026 static long maxMem = 0;
Mathieu Chartier987ccff2013-07-08 11:05:21 -070027
28 static class NativeAllocation {
29 private int bytes;
30
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
42 protected void finalize() throws Exception {
43 synchronized (nativeLock) {
44 nativeBytes -= bytes;
45 }
46 register_native_free.invoke(runtime, bytes);
47 }
48 }
49
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);
Mathieu Chartiere03df652014-09-02 17:36:08 -070056 maxMem = Runtime.getRuntime().maxMemory();
Mathieu Chartier987ccff2013-07-08 11:05:21 -070057 int count = 16;
Mathieu Chartiere03df652014-09-02 17:36:08 -070058 int size = (int)(maxMem / 2 / count);
Mathieu Chartier987ccff2013-07-08 11:05:21 -070059 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