Java memory questions about 'new' keyword

前端 未结 3 1159
小鲜肉
小鲜肉 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条回答
  • 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).

    0 讨论(0)
  • 2021-01-05 02:29

    Is String x allocated on the stack or on the heap?

    x isn't a String. It is a reference to a String. The reference is a local variable, and so goes on the stack. The String is an object, and so goes on the heap.

    Will the program eventually crash because of a memory overflow

    Probably not.

    or will garbage collection prevent that?

    It should.

    Does the new keyword always create the object on the heap?

    Yes.

    When is an object created on the stack?

    Never ... unless the JVM decides it cannot escape the current scope and so decides to do so.

    0 讨论(0)
  • 2021-01-05 02:44

    Using new, yes, puts objects on the heap. Objects that are no longer accessible by any thread can be garbage collected. Whether you run out of memory or not depends on the size of data your program uses, and if you are good at 'releasing' objects you dont need any more (think: memory leaks are bad).

    In your example, you will be running the garbage collector like crazy, which I think is what you are intending to demonstrate.

    Local variables go on the stack.

    0 讨论(0)
提交回复
热议问题