user2269707
user2269707

Reputation:

Can I suggest JVM when to do the garbage collection?

I used a event based framework in my java code and there's an event which will triggered when no other events are coming, let's say it's a thread idle event. I think this is a good time to do the GC since doing GC in the time will have no influence on other jobs.

So: 1, Is there any way I can do this? 2, Should I do this?

Upvotes: 1

Views: 131

Answers (2)

Mateusz Stefek
Mateusz Stefek

Reputation: 3856

1) System.gc()

2) Should I do it?

The root of all evil is premature optimization

I doubt it will help and there’s a high chance that it will degrade performance. What do you want to optimize? Throughput or latency? How do you measure it? It is really hard, as with gc you should simulate a production-like environment. System.gc() does a full gc, so it might introduce long pauses where short young generation pauses would have been acceptable.

Note that the G1 garbage collector already automatically adjusts itself to the system load.

Upvotes: 0

Dilyano Senders
Dilyano Senders

Reputation: 199

To answer your questions:

You can tell the JVM to initiate Garbage Collection, But the JVM will decide if and when it will garbage collect. Objects which aren't used anymore, will automatically Garbage collected. If you really want to SUGGEST the JVM to run a Garbage Collection you should use this line of code:

System.gc();

But as I said, the JVM will see when it isn't used anymore garbage collection it when it wants/needs to.

Upvotes: 1

Related Questions