Automatically release unused memory in ImageJ / Fiji

hthms picture hthms · Apr 7, 2014 · Viewed 9.3k times · Source

I use Fiji/ImageJ on Windows and encountered the following problem: when I close a file, the memory allocated for that file is not released. ImageJ keeps that memory allocated, and reuses it when other files are opened.

So this is not strictly a memory leak, but still highly annoying, especially when working with large files. Is there a manual or (preferably) automatic way to trigger garbage collection after images are closed?

Edit:

Example: I use a large file and windows task manager to check memory allocation.

  1. clean start: 9278K of 12123MB in ImageJ, 3.56GB/16GB used in task manager.
  2. open large raw file: 5928MB of 12123MB, 9.41/16GB in task manager
  3. close large file: 9253K of 12123MB, 9.43/16GB GB in task manager. Fiji-win64.exe still uses 6419188K memory in task manager.
  4. Close Fiji: 3.28 GB / 16GB in task manager.

My problem is that I normally always keep Fiji open with a few files and windows. Then I open some large files and eventually close them, but ImageJ still keeps my memory reserved. Then I start executing a memory hungry job, and I quickly run out of memory and the whole system hungs up when windows starts swapping things.

Answer

Josef Borkovec picture Josef Borkovec · Apr 8, 2014

Whether java returns unused memory to OS depends on the used garbage collector. Some implementations do return it and in some, the heap only keeps growing. Which garbage collector is used by default differs in various JRE versions and is also dependent on the system.

You can force what garbage collector is used by command line arguments when java is started. To change the used gc for ImageJ to one of gcs that return unused memory, edit ImageJ.cfg file in the ImageJ install directory and on the third line add -XX:+UseParNewGC.

For fiji, run the fiji launcher with -XX:+UseParNewGC added to command line arguments, i.e. ImageJ-win64.exe -XX:+UseParNewGC --

On my system with 64-bit java 8, this leads to memory being released back to OS. This is a graph of memory usage of ImageJ when importing a big stack, duplicating it a few times, closing it and running garbage collector a few times:

ImageJ memory usage

See this usefull article on how different gcs behave with respect to returning memory.