Here is the brutal reality. Asking the JVM to run garbage collection is a polite suggestion, not a command. Calling System.gc() or Runtime.getRuntime().gc() sends a request to the garbage collector, and the collector answers when it feels like it. That means tests that hinge on forced collection can be flaky and dramatic in production.
Use explicit collection only during controlled debugging and testing. Want to reproduce a leak, verify that weak references are cleared, or measure how many objects survive a collection step? Fine. Otherwise leave GC to its job and get on with your life.
System.gc()
Runtime.getRuntime().gc()
These are your gentle taps on the JVM shoulder. They are widely supported and safe in tests, but they do not guarantee a full or immediate collection. Use them sparingly and wrap expectations with retries or timeouts if you rely on them in assertions.
Sometimes you want to trigger GC without changing the code. Tools are your friends here.
jcmd 12345 GC.run
jmap -dump live,format=b,file=heap.hprof 12345
External triggers are useful during live debugging because they do not require code changes or redeploys.
If you need deterministic behavior in a CI or local experiment, adjust JVM flags and logging. Useful flags include
-XX:+ExplicitGCInvokesConcurrent
which changes how explicit GC calls are handled-XX:+UseG1GC
which uses the G1 collector and can alter collection patterns-Xlog gc*
or classic logging flags like -XX:+PrintGCDetails
for observing what actually happenedThese flags let you see and influence the collector behavior in test runs. Do not assume the same flags are needed in production.
A log entry that says GC ran is not the same as proof that the objects you expected were reclaimed. Use heap dumps and profilers to confirm. Compare before and after snapshots, and inspect retained sizes and dominator trees to know what actually survived.
Do not call explicit GC in production unless you enjoy performance surprises. Forced requests can interact badly with concurrent collectors, cause unexpected pauses, and make latency budgets cry. If you must use explicit triggers in production, document why, and put telemetry and kill switches in place.
Bottom line, be polite but suspicious. Ask the JVM to run GC when needed, but always verify with logs and heap dumps. Treat System.gc as a helpful hint, not an ultimatum, and your tests will stop playing mind games with you.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.