I've read why is it bad practice to call System.gc(), and many others, e.g. this one describing a really disastrous misuse of System.gc()
. However, there are cases when the GC takes too long and avoiding long pauses, e.g., by avoiding garbage is not exactly trivial and makes the code harder to maintain.
IMHO calling GC manually is fine in the following common scenario:
- There are multiple interchangeable webserves with a failover in front of them.
- Every server uses a few gigabytes of heap and the STW pauses take much longer than an average request.
- The failover has no idea when GC is going to happen.
- The failover can exempt a server when told to.
The algorithm seems to be trivial: Periodically select a server, let no more requests be send to it, let it finished its running requests, let it do its GC, and re-activate the server.
I wonder if I am missing something?1,2
What are the alternatives?
Long running requests could be a problem, but let's assume there are none. Or simply limit waiting to some period comparable with what GC takes. Making a slow request even slower doesn't sound too bad.
An option like
-XX:+DisableExplicitGC
could make the algorithm useless, but just don't use it (my use case includes dedicated servers I'm in charge of).