You can garbage collect in Java simply by calling System.gc() but sometimes this \"stalls\" the application. Is it a bad idea to garbage collect like this and a
As others have said, calling System.gc() is usually a mistake. (Not always ... )
Assuming that you have one of those rare use-cases where calling System.gc() is likely to be beneficial, there are two cases to consider:
If your JVM is using a classical "stop the world" collector, then running it in a separate thread will make no difference. The GC stops all application threads for the duration.
If your JVM is running a concurrent collector, then running it in a separate thread may be a good idea. It is true that all collectors have a phase in which all threads are stopped, but calling System.gc() is documented as returning after "the Java Virtual Machine has made a best effort to reclaim space from all discarded objects". So running it in a separate thread will allow the current thread to do something else. However, you need to be careful to avoid launching multiple threads that each call System.gc(); i.e. the code that is responsible for launching the thread needs to keep track of any previous GC threads.