Is it possible to force JVM to create an object in stack other than heap?

天涯浪子 提交于 2019-12-05 18:20:44

There is no way to force the JVM to allocate objects anywhere. You should not care where Java actually allocates your Object because it is not defined in the specifications. That being said the JVM has gotten a lot smarter and using a technique called escape analysis it can, if it wants to, allocate an object on the stack. There is however no way to force the JVM to allocate an Object at a specific place and it is not required by the specification that this behavior happen.

If talk about HotSpot JVM, it never allocates Java objects on a stack. However there is an optimization: when Escape Analysis can prove that an object reference does not escape the scope being compiled, JIT eliminates an allocation at all and replaces the object fields with the local variables.

Note: we cannot claim this an allocation on a stack since the object does not exist, e.g. calling Object's methods like hashCode or wait is not possible.

Whenever JVM can eliminate the allocation, it does so automatically.
If it cannot - there is no way to force it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!