How to deal with “java.lang.OutOfMemoryError: Java heap space” error?

后端 未结 21 1690
死守一世寂寞
死守一世寂寞 2020-11-21 04:49

I am writing a client-side Swing application (graphical font designer) on Java 5. Recently, I am running into java.lang.OutOfMemoryEr

21条回答
  •  灰色年华
    2020-11-21 05:13

    I read somewhere else that you can try - catch java.lang.OutOfMemoryError and on the catch block, you can free all resources that you know might use a lot of memory, close connections and so forth, then do a System.gc() then re-try whatever you were going to do.

    Another way is this although, i don't know whether this would work, but I am currently testing whether it will work on my application.

    The Idea is to do Garbage collection by calling System.gc() which is known to increase free memory. You can keep checking this after a memory gobbling code executes.

    //Mimimum acceptable free memory you think your app needs
    long minRunningMemory = (1024*1024);
    
    Runtime runtime = Runtime.getRuntime();
    
    if(runtime.freeMemory()

提交回复
热议问题