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的垃圾回收器是被设计用来解决内存释放问题的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值