Thinking in java-10 对象创建和生命周期

1.对象创建

Object creation:
1). For maximum runtime speed, the storage and lifetime can be determined while the program is being written, by placing objects on the stack (sometimes called automatic or scoped variables) or in the static storage area.
2). The second approach is to create objects dynamically in a pool of memory called the heap. In this approach, you don’t know until runtime how many objects you need, what their lifetime is, or the exact type is, which are determined at the spur of the moment while the program is running.
Java uses the dynamic memory allocation, exclusively (primitive types, are a special case). Every time you want to create an object, you use the new operator to build a dynamic instance object.
Lifetime:
Non-java languages: allow object created on the stack, the compiler determines how long the objects lasts and can automatically destroy it. If you create it on the heap, the compiler has no knowledge of its lifetime, programmers determine when to destroy the object, which can lead to memory leak if not done correctly.
Java: garbage collector, designed to take care of the problem of releasing the memory.

栈–stack

出于运行速度的考虑,如果把对象存放在栈上(有时叫做自动或者局部变量)或静态内存区域,在程序编写时存储位置和其生命周期都能够确定。

堆–heap

另一种动态在内存上创建对象的方式是在heap堆上操作的。这种方式下,我们并不知道我们需要多少对象,我们也不知道对象的生命周期是怎样的,甚至对象的确切类型也不清楚。所有这些只有在程序运行的那一刻才能确定。

Java使用的是动态内存分配的方式(除了对于基本数据类型外),每次我们创建一个对象,我们使用new操作符创建一个动态的实例对象。

2.生命周期

生命周期lifetime:决定了对象持续的时间和销毁的时刻。
对于一些non-java语言:允许对象在栈上创建,编译器决定对象存在的时间并能自动地销毁对象。如若在堆上创建对象,编译器并不知道对象的生命周期,由程序员决定销毁对象的时间;所以如果操作不当可能造成内存溢出问题。
对于Java语言:Java的垃圾回收器是被设计用来解决内存释放问题的。

你可能感兴趣的:(垃圾回收,stack,heap,Creation,lifetime)