Java memory questions about 'new' keyword

前端 未结 3 1158
小鲜肉
小鲜肉 2021-01-05 01:43

What happens if you run the following code..

while (true) {
    String x = new String(\"ABC\");
}

in terms of memory?

Is String x a

3条回答
  •  -上瘾入骨i
    2021-01-05 02:24

    In theory, new creates on the Heap, and non-objects (i.e., ints, chars and so on) are created on the stack. The only exception, afaik, are strings, created on the stack as well. In practice, the JIT compiler of many modern JVMs will see that, in some cases, objects created with new can be created on the stack (for example, local objects that are not referenced outside of the current function).

    The garbage collector will take care of the deallocation for you, that's its purpose, but of course you can run out of memory if you create and keep references on too many objects at the same time (try creating a list with a billion strings, for example).

提交回复
热议问题