Java memory questions about 'new' keyword

前端 未结 3 1168
小鲜肉
小鲜肉 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: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.

提交回复
热议问题