Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deterministic garbage collection in JVM

I wonder if there are any instances in which the hotspot JVM or any other JVMs can deterministically garbage collect. I'm aware of escape analysis but wonder if it works for heap allocated objects too. What I mean is in C++ code such as this gives deterministic garbage collection off the heap

#include <vector>
int main(int argc, char*argv[]){
    std::vector<double> v_somevector;
} // std::vector::~vector() is called determinitically

Surely in Java something like

.
.
.
private double ma() throws Exception{
    double result = 0.0;
    final double[] closes = new double[100000];
    //perform some calculation using the closes array above
    return result;
} // At this point why shouldn't closes be deterministically garbage collected (as in immediately)?

Should be deterministic in garbage collecting the closes array. For what it seems, escape analysis seems to focus on the possibility of allocating the closes array on the stack but even if allocated on the heap, in this case I don't see why it can't be collected on leaving ma()'s scope

like image 713
Michael Avatar asked Dec 01 '25 05:12

Michael


2 Answers

It certainly could be; the Java specification doesn't prohibit it. It just leaves the question of garbage collection entirely up to the implementation. A JVM doesn't even actually have to implement garbage collection at all!

The reason for this is simply that there are a number of techniques that a JVM can use that will be probabilistically more efficient than the sort of synchronized allocation you are talking about, such as generational heaps and concurrent mark-and-sweep. You'd be free to implement the sort of logic you're talking about in your own VM, but profiling has demonstrated that for many business-type workloads, a large majority of the CPU usage in C++ programs is taken up by construction and destruction of objects, and approaches like generational heaps streamline a lot of the memory management.

like image 165
chrylis -cautiouslyoptimistic- Avatar answered Dec 03 '25 22:12

chrylis -cautiouslyoptimistic-


What you are talking about is not so much deterministic as eager garbage collection, and if the JVM really treated you to it, you would have regretted your wish. Eager GC is inefficient both at the de-allocation and the allocation side: it forces the runtime to handle memory in a way too granular fashion, precluding many optimization opportunities and causing heap fragmentation.

If you truly care about performance, then you want your GC-ing done wholesale, and that is precisely what HotSpot does.

like image 21
Marko Topolnik Avatar answered Dec 03 '25 22:12

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!