The other answers are correct that Java will use as much memory as it is allowed, and at this point it will collect garbage. To get around this, you can specify a smaller heap size in the JVM settings. You do this with the -Xmx setting. For example, if you think you only need 32 MB, run it as:
java -Xmx32M [your main class or jar here]
The heap of your program (non-stack memory) will never take more than 32 MB, but it will crash if it needs more than immediately (and where you need to profile). I do not see any obvious leaks in your program (assuming ImageIO does not require any cleaning), so I think that everything will be fine.
source share