1 /* 2 * Copyright (C) 2009 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 public class Main { 18 static class ArrayMemEater { blowup(char[][] holder, int size)19 static int blowup(char[][] holder, int size) { 20 int i = 0; 21 try { 22 for ( ; i < size; i++) 23 holder[i] = new char[128]; 24 } catch (OutOfMemoryError oome) { 25 return i; 26 } 27 28 return size; 29 } 30 confuseCompilerOptimization(char[][] holder)31 static void confuseCompilerOptimization(char[][] holder) { 32 } 33 } 34 35 static class InstanceMemEater { 36 InstanceMemEater next; 37 double d1, d2, d3, d4, d5, d6, d7, d8; 38 blowup()39 static InstanceMemEater blowup() { 40 InstanceMemEater memEater; 41 try { 42 memEater = new InstanceMemEater(); 43 } catch (OutOfMemoryError e) { 44 memEater = null; 45 } 46 return memEater; 47 } 48 confuseCompilerOptimization(InstanceMemEater memEater)49 static void confuseCompilerOptimization(InstanceMemEater memEater) { 50 } 51 } 52 triggerArrayOOM()53 static void triggerArrayOOM() { 54 int size = 1 * 1024 * 1024; 55 char[][] holder = new char[size][]; 56 57 int count = ArrayMemEater.blowup(holder, size); 58 ArrayMemEater.confuseCompilerOptimization(holder); 59 if (count < size) { 60 System.out.println("Array allocation failed"); 61 } 62 } 63 triggerInstanceOOM()64 static void triggerInstanceOOM() { 65 InstanceMemEater memEater = InstanceMemEater.blowup(); 66 InstanceMemEater lastMemEater = memEater; 67 do { 68 lastMemEater.next = InstanceMemEater.blowup(); 69 lastMemEater = lastMemEater.next; 70 } while (lastMemEater != null); 71 memEater.confuseCompilerOptimization(memEater); 72 System.out.println("Instance allocation failed"); 73 } 74 main(String[] args)75 public static void main(String[] args) { 76 triggerArrayOOM(); 77 triggerInstanceOOM(); 78 } 79 } 80