代码之家  ›  专栏  ›  技术社区  ›  Gilbeg

如何在64位Linux JVM上发生OutOfMemoryError

  •  3
  • Gilbeg  · 技术社区  · 15 年前

    在我的单元测试中,我故意尝试引发OutOfMemoryError异常。我使用如下简单语句:

    byte[] block = new byte[128 * 1024 * 1024 * 1024];
    

    该代码在Win7 64位上运行,jdk6u21 64位。但是当我在Centos 5 64位jdk6u21上运行这个程序时,不会抛出OutOfMemoryError,即使我将数组的大小调大了。

    7 回复  |  直到 15 年前
        1
  •  4
  •   pgras    15 年前

    如果只想消耗所有内存,请执行以下操作:

        try {
            List<Object> tempList = new ArrayList<Object>();
            while (true) {
                tempList.add(new byte[128 * 1024 * 1024 * 1024]);
            }
        } catch (OutOfMemoryError OME) {
           // OK, Garbage Collector will have run now...
        }
    
        2
  •  5
  •   Matthew Flaschen    15 年前

    Linux并不总是能立即为您分配所需的所有内存,因为许多实际应用程序所需的内存超出了它们的需要。这被称为过度限制(它也意味着有时它猜错了,而恐惧 OOM killer

    对于你的单元测试,我会 OutOfMemoryError 手动。

        3
  •  3
  •   Ha.    15 年前

        4
  •  1
  •   Slartibartfast    15 年前
    ulimit -v 102400 
    ulimit -d 102400
    unitTest.sh
    

    man 2 setrlimit 关于如何在引擎盖下工作的细节。 help ulimit 对于ulimit命令。

        5
  •  1
  •   dimdm    15 年前

    您可以通过使用 -Xmx 旗帜。

    启动以下程序:

    
    public final class Test {
    
      public static void main(final String[] args) {
        final byte[] block = new byte[Integer.MAX_VALUE];
      }
    
    }
    

    -Xmx8m

    这样就可以了:

    
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at Test.main(Test.java:4)
    
        6
  •  1
  •   Peter Lawrey    15 年前

    次要点,但分配新的long[Integer.MAX\u VALUE]将占用8倍的内存(~每个16 GB)

        7
  •  0
  •   mdma    15 年前

    没有OutofMemoryError的原因是内存分配处于未提交状态,没有页面。