I want to use stack as an my heap management system(In other world, I want to use stack instead of heap) to allocate and free objects. I know that allocation would be very fast and just can be simulated by increasing stack pointer. But my question is that when I using a garbage collection algorithm like mark and sweep how can I free the objects on sweep phase? Since stack is LIFO, it is possible that last object in the stack is alive and the objects below it are candidate to be freed! So how can I do the sweep phase?(because the last objects in the stack is alive and without popping it, it is impossible to free the below objects) And also how can I deal with fragmentation in the stack??
3 Answers
I want to use stack as an my heap management system
It is not possible in Java1.
But my question is that when I using a garbage collection algorithm like mark and sweep how can I free the objects on sweep phase?
This very hypothetical since you can't do this in Java2, but if you are storing objects on the heap, then they are never garbage that the garbage collector needs to deal with. (And in fact, the whole point of putting them on the heap is to avoid the GC having to deal with them.)
1 - ... except in the edge case where you are using JNI to call a native method, and the native method is doing it during the method call. In some recent versions of Java, the JIT compiler is capable of spotting some situations an object can be safely allocated on the stack ... and doing it. But that happens transparently. The JIT compiler does it ... not you.
2 - It is not impossible to design and implement a programming language that is both garbage collected, and it allows you to allocate on the heap. However, making the implementation type safe would be difficult. The language design would need a way to prevent pointers to objects one the stack from being stored in heap objects. And I think that would make the language complicated, and hard to understand. IMO, it is not worth it.
1 Comment
Actually, Java will allocate on stack when, following escape analysis, the allocated object is known not to be used outside of the current method.
Comments
That's the point of a heap versus a stack. Heaps support holes while stacks do not. You could easily use a heap like a stack, with a single pointer to the "end" of the heap, quickly incrementing it to allocate new objects, but then you run into the same problem on cleanup - how to get the space back.
Unless freeing of objects can be guaranteed to happen in exactly reverse order of allocation, a stack is going to be challenging to use as a heap.
StackandHeap, since the one cannot be easily substituted by the other.