简体   繁体   English

如何在此Java代码中处理堆内存不足?

[英]How to deal with out of heap memory in this Java code?

I'm using JMatIO to read Matlab .mat file into my Java program. 我正在使用JMatIO将Matlab .mat文件读入Java程序。 But when my code executed, it reported out of memory error: 但是当我的代码执行时,它报告内存不足错误:

java.lang.OutOfMemoryError: Java heap space

My program is just reading a mat file which is about 27M in size. 我的程序只是读取一个大小约为27M的mat文件。 I've tried using several -Xmx and -Xms VM options to increase the heap size but it didn't help. 我尝试使用多个-Xmx-Xms VM选项来增加堆大小,但没有帮助。 My code is as follows: 我的代码如下:

public class ReadMat {
    private MatFileReader reader;

    public ReadMat(File f) {
        try {
            reader = new MatFileReader(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        File matFile = new File("test.mat");
        ReadMat rmat = new ReadMat(matFile);
    }
}

test.mat is just a Matlab mat file which is about 27M. test.mat仅仅是一个Matlab mat文件,大约27M。 It will report OutOfMemoryError once I run it. 一旦运行它,它将报告OutOfMemoryError So how to solve this problem? 那么如何解决这个问题呢?

There are two problems. 有两个问题。 One is that in any conversion routine like this you generally have to hold the source array in memory while you convert it or load it. 一个是,在任何此类转换例程中,通常都必须在转换或加载时将源数组保留在内存中。 So the whole 27M file is in memory to begin with and this could be larger because the holding buffer may be larger. 因此,整个27M文件从内存开始,并且可能更大,因为保持缓冲区可能更大。

Secondly, JMatIO is probably converting the primitive types into Objects. 其次,JMatIO可能会将原始类型转换为对象。 For example, if the original file has shorts in it, each using up 2 bytes and you convert each of these to an Object which take, say, 16 bytes then your memory usage increases significantly. 例如,如果原始文件中包含短裤,每个短裤都占用2个字节,然后将每个短裤转换为一个占用16个字节的对象,那么您的内存使用量将大大增加。

If changing the minimum and maximum sizes for the JVM heap are not fixing the problem, then you need to evaluate how MatFileReader reads test.mat into memory. 如果更改JVM堆的最小和最大大小不能解决问题,则需要评估MatFileReader如何将test.mat读入内存。 I'm willing to bet that the object allocation of MatFileReader during the reading of the file is what is causing the OutOfMemoryError. 我敢打赌,在读取文件期间MatFileReader的对象分配是导致OutOfMemoryError的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM