简体   繁体   中英

Memory leak in Java Simulation. Will nulling a parent class fix?

I have developed simulation software for a robotics competition coming up. This software's purpose is to learn how to play a game using NEAT.

To do this the simulation must be run many many many times. However, I've just recently noticed a bad memory leak in the program. It appears that every 10 seconds 1 more mb of memory is allocated.

I believe that the memory leak lies within my Game class because this class is actually responsible for running through the simulation.

My question is:

If I were to set game to null before starting another game would that allow the garbage collector to deallocate every child object within game or do I also have to set those to null.

Would this do the trick?

{

    //=-=-=-=-=-=-=-=-=--=-=-=-=-=-=
    Game game = new Game(someParams);

    while(!(game.isFinished()))
    {
        game.run();
        game.draw();
    }

    //do some stuff for NEAT

    //remove the memory
    game = null;
    System.gc();
    //=-=-=-=-=-=-=-=-=-=-=-=-=-

}

At the beginning of this method you assign a brand new instance to game. Setting it to null at the end might help depending on what you do after. If this is the end of the method, the setting it to null will change nothing, because the game reference is destroyed immediately after (as if you had assigned null). If you continue doing things in the same method after setting it to null, it might help, but it won't be the final solution.

Memory leaks in Java usually happen because you forget to release a reference to an object. For instance adding it to a list, and forgetting to remove it when you are over with it.

JDK provides some tools for that:

$ jmap -dump:format=b,live,file=/tmp/dump <pid>
$ jhat /tmp/dump

jhat creates a HTTP server listening on port 7000. Open http://localhost:7000 with your browser and at the end of the first page you'll find the option "Show instance counts for all classes (excluding platform)."

Click on it and you will see a list of all the loaded classes, ordered by the number of instances. One or two of the classes will have an abnormally-high number of instances. Click on "instances" and you will have the list of all the instances for that class.

Clicking on one of the instances you'll see the actual object, and under "References to this object" a list of objects keeping a reference to it.

Some referencing objects will have valid references to it. Others might have a forgotten reference. Try to identify which object (a List, a Map, a Set, etc), keeps a forgotten reference by checking several instances of the objects which is not being released.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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