15

how could I request Java garbage collection externally, starting the program from JAR (Windows BAT used)?

  • From the Java code I can do it with System.gc()
  • When running a JNLP distribution, I get this "Java console" turned on from Control Panel / Java / ... and this Java console provides manual garbage collection.

But... When I'm running the jar from command-line / bat the java console doesn't seem to open. Couldn't find help with a brief googling, maybe somebody here?

Touko
  • 11,359
  • 16
  • 75
  • 105
  • Looks like dublicate of https://stackoverflow.com/questions/3523837/how-do-you-force-garbage-collection-from-the-shell, the link have top answer here as top answer there too. – Alex Martian Aug 14 '19 at 10:13

4 Answers4

16

For a purely command-line approach, you should be able to use jcmd. I believe jcmd has been part of the standard JDK install since at least Java 1.7. The command would be something like this:

jcmd <process-id> GC.run

You can get a list of available diagnostic commands that jcmd provides for a particular process like this:

jcmd <process-id> help
Ogre Psalm33
  • 21,366
  • 16
  • 74
  • 92
11

You can use jconsole to connect to a JVM that is running locally - This provides a "Perform GC" button on the GUI.

You'll need to specify -Dcom.sun.management.jmxremote when you kick off your java process.

Peter
  • 5,793
  • 4
  • 27
  • 31
5

If you use the very latest java 6 you also have jvisualvm which complements and extend the jconsole functionality. They are both very useful tools.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
1

You normally should not have any reason to force garbage collection. Doing so, messes up the garbage collector algorithms (mainly their performance). It will also slow down the program while garbage is being collected. If there is a memory issue, you should use memory tracing tools to find out where references are being held? (Are listeners unregistered?)

As in the other answers, you can use jconsole or jvisualvm. You can also use jmx to do it programmatically.

Paul de Vrieze
  • 4,888
  • 1
  • 24
  • 29
  • There are many legit uses to force GC collection. One is for test purpose. Another example: if you are developing in a low memory system with SSD swap. Java does not know if the memory is "fast memory" or swap. So Java tends to use all free memory before automatically fire GC. Fire GC manually can help a lot in this case. Obviously it is not recommended in any case of server production use (at least I can't image one now). – Felipe Oct 14 '15 at 03:24