为了测试目的,我需要故意创建一个内存不足的实例。有谁知道最快的方法来做到这一点?
			
			2810 次
		
3 回答
            15        
        
		
取决于您要做什么,但这应该足够了:
double[] d = new double[Integer.MAX_VALUE];
于 2012-04-05T19:40:30.387   回答
    
    
            1        
        
		
import java.util.ArrayList;
class TestOome {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        byte[] buffer = new byte[2^20];
        ArrayList<String> list = new ArrayList<String>();
        try {
            while (true) {
                list.add("Lollygobblenlissbomb");
            }
        } catch (Throwable t) {
            long end = System.currentTimeMillis();
            buffer = null;
            System.err.println(t + " in " + (end-start) + " millis.");
        }
    }
}
本地输出
java.lang.OutOfMemoryError: Java heap space in 1152 millis.
Press any key to continue . . .
    于 2012-04-05T19:46:39.283   回答
    
    
            0        
        
		
运行一个递归函数,它在没有基本/锚点的情况下调用自己。每个递归调用都会创建一个堆栈。所以应该很快。
于 2012-04-05T19:37:18.933   回答