Java robot Garbage Colloection

Does Garbage Collection help Java code on our Frc Robot ?

This Week my team is running a stem camp an I was wondering if Forcing an Java-Garbage collection on the Roborio would add any improvements to our robot code ?

p.s sorry for bad grammer, im the head programmer on my team


GC is an inescapable part of Java as a programming language. So long as you’re not experiencing slowdowns or stutters or running crazy multi-threaded things on your roboRIO such as your own vision code, it’s probably not worth the time to fine-tune.

OK thank you i was just curious about the topic

I’ll assume you are still curious :).

Yes and No.

Garbage Collection is necessary for a language like Java. With the way most programs are written, objects will be created and destroyed at runtime. Once an object no longer has any references, it is simply taking up space in RAM and ought to be removed. Failure to do so will result in “out of RAM” issues, even though your program is not actually using much RAM.


Garbage collection can take an indeterminate amount of time. Doing it randomly at runtime is generally bad. Robots depend on the fact that your periodic() functions get called at a regular 20ms rate. If you randomly have to wait 500ms for garbage collection to finish, you may notice your robot occasionally stutter or stop. This is a key historical argument against using Java, and is the reason why, professionally, I would never use a garbage collecting language for a professional, production real-time solution.


Messing with garbage collection can also produce weird side effects and is often not super effective. The smart folks who made the JVM did a good job at picking the “least evil” solutions for getting garbage collection working well - regardless of whether your application has to run real-time or not, no one likes code that randomly stutters.

The easiest answer within Java is to minimize the usage of the keyword new. Do all your object creation in robotInit(), and don’t repeatedly del or new objects at runtime, without good reason.

I have seen teams that attempt to use System.gc(); to force a garbage collect operation while the robot is disabled, but I’m not clear on if this is actually effective, or a recommended practice.

1 Like

oh OK , so its best to leave gc to java jvm then .

I was just trying to save some robot ram for background bot programs / like our robots ping time monitor


Yup, Unless you’ve got a very specific problem you’re stuck on, I’d leave it as-is.


This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.