1/*
2 * Copyright (C) 2014 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.Vector;
18
19public class Main {
20    static char [][] holder;
21
22    static class ArrayMemEater {
23        static boolean sawOome;
24
25        static void blowup(char[][] holder) {
26            try {
27                for (int i = 0; i < holder.length; ++i) {
28                    holder[i] = new char[1024 * 1024];
29                }
30            } catch (OutOfMemoryError oome) {
31                ArrayMemEater.sawOome = true;
32            }
33        }
34    }
35
36    static class InstanceFinalizerMemEater {
37        public void finalize() {}
38    }
39
40    static boolean triggerArrayOOM(char[][] holder) {
41        ArrayMemEater.blowup(holder);
42        return ArrayMemEater.sawOome;
43    }
44
45    static boolean triggerInstanceFinalizerOOM() {
46        boolean sawOome = false;
47        try {
48            Vector v = new Vector();
49            while (true) {
50                v.add(new InstanceFinalizerMemEater());
51            }
52        } catch (OutOfMemoryError e) {
53            sawOome = true;
54        }
55        return sawOome;
56    }
57
58    public static void main(String[] args) {
59        // Keep holder alive to make instance OOM happen faster.
60        holder = new char[128 * 1024][];
61        if (!triggerArrayOOM(holder)) {
62            // The test failed here. To avoid potential OOME during println,
63            // make holder unreachable.
64            holder = null;
65            System.out.println("NEW_ARRAY did not throw OOME");
66        }
67
68        if (!triggerInstanceFinalizerOOM()) {
69            // The test failed here. To avoid potential OOME during println,
70            // make holder unreachable.
71            holder = null;
72            System.out.println("NEW_INSTANCE (finalize) did not throw OOME");
73        }
74
75        // Make holder unreachable here so that the Sentinel
76        // allocation in runFinalization() won't fail.
77        holder = null;
78        System.runFinalization();
79    }
80}
81