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
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.