使用字符串利用最大内存

时间:2013-01-26 10:01:53

标签: java string garbage-collection

有没有办法利用strings来利用系统的最大内存? 我正在使用runtime来显示可用内存。我试过这段代码:

class Mem{
       public static void main(String[] args) {
              System.out.println(Runtime.getRuntime().maxMemory());
              System.out.println(Runtime.getRuntime().totalMemory());
              System.out.println(Runtime.getRuntime().freeMemory());
              String str=new String("Hi");
              for(long i=0;i<1000000;i++){
                     str+="aa";
                     //System.out.println(i);
              }      
              System.out.println(Runtime.getRuntime().freeMemory());
       }
}

然而,garbage collector每隔几次迭代就会生效,并释放内存。可以使它利用最大内存并在gc释放它之前显示空闲内存吗?

4 个答案:

答案 0 :(得分:4)

快速分配和保存大量内存的方法是

List<byte[]> bytes = new ArrayList<>();
for(int i = 0; i < 1000; i++)
    bytes.add(new byte[10000000]); // 10 MB

答案 1 :(得分:3)

str+="aa";每次都会创建一个新字符串并重新分配str,以便旧字符串可以进行垃圾回收。

但如果迭代足够,它会在某个阶段耗尽内存。

你应该把for循环放在try / catch块中,捕获OutOfMemoryError并在catch块中包含你的print语句。

答案 2 :(得分:3)

最后,您的字符串只包含200万个字符。如果您想让代码耗尽内存,请更改

        str += "aa";

        str += str;

这将使字符串呈指数级增长,即使进行适度的迭代,也不会有任何垃圾收集量。

答案 3 :(得分:3)

尝试类似

的内容
    System.out.println(Runtime.getRuntime().maxMemory());
    System.out.println(Runtime.getRuntime().totalMemory());
    System.out.println(Runtime.getRuntime().freeMemory());
    String str = new String(new char[32_000_000]);
    System.out.println(Runtime.getRuntime().totalMemory());
    System.out.println(Runtime.getRuntime().freeMemory());

请注意,str += "aa"速度太慢,您可能会得出错误的结论。在你的情况下GC不能释放任何内存