Вопрос:

Java memory questions about 'new' keyword

java memory stack heap

1578 просмотра

3 ответа

1602 Репутация автора

What happens if you run the following code..

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

in terms of memory?

Is String x allocated on the stack or on the heap? Will the program eventually crash because of a memory overflow, or will garbage collection prevent that? Does the new keyword always create the object on the heap? When is an object created on the stack?

Thanks!

Автор: Rohan Agarwal Источник Размещён: 25.02.2013 09:08

Ответы (3)


2 плюса

28025 Репутация автора

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.

Автор: vikingsteve Размещён: 25.02.2013 09:12

-1 плюса

5307 Репутация автора

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).

Автор: Fabien Размещён: 25.02.2013 09:13

7 плюса

271204 Репутация автора

Решение

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.

Автор: user207421 Размещён: 25.02.2013 09:14
Вопросы из категории :
32x32