初始化Array时出错:OutOfMemoryError

Rog*_*ews 0 java out-of-memory

我必须int input[]根据配置参数的高度和宽度为数组分配空间.

int input[]=new int[height * width]; //this is line no 538
Run Code Online (Sandbox Code Playgroud)

其中一个配置有参数height=8192width=8192.所以数组的大小就变成了67108864.但是当我这样做时,我得到OutOfMemoryError.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at Test.main(Test.java:538)
Run Code Online (Sandbox Code Playgroud)

我已经在eclipse以及cygwin上运行了这个程序,但我遇到了同样的问题.我认为这不是错误,也不是例外.我怎么能纠正这个?

Ada*_*cin 5

由于8192*8192*4 = 256 M(整数各为4个字节),因此您的矩阵本身使用256 MB的堆空间.

您可以告诉JVM应用程序可以使用多少堆空间.从运行man java和查看非标准选项:

-Xmxn

            Specify the maximum size, in bytes, of the memory allocation
            pool. This value must a multiple of 1024 greater than 2MB.
            Append the letter k or K to indicate kilobytes, or m or M to
            indicate megabytes. The default value is chosen at runtime
            based on system configuration. For more information, see
            HotSpot Ergonomics
            Examples:

                   -Xmx83886080
                   -Xmx81920k
                   -Xmx80m

         On Solaris 7 and Solaris 8 SPARC platforms, the upper limit for
         this value is approximately 4000m minus overhead amounts. On
         Solaris 2.6 and x86 platforms, the upper limit is approximately
         2000m minus overhead amounts. On Linux platforms, the upper limit
         is approximately 2000m minus overhead amounts.
Run Code Online (Sandbox Code Playgroud)

要使用此选项,您可以使用类似命令启动应用程序

java -Xmxn1024m -jar foo.jar
Run Code Online (Sandbox Code Playgroud)

在Eclipse中,您也可以添加命令行选项. eclipse.org上的这个页面描述了如何向Java程序添加命令行参数.您应该将-Xmxn1024m(或其他足够大的堆规范)添加到该站点上显示的对话框的"VM参数"部分.