java垃圾处理机制

java文件通过编译器(javac命令)生成class文件(字节码文件),其通过java命令启动虚拟机将字节码文件转换成平台能够理解的方式运行。
类存在于源文件里面,方法存在于类中,语句存在与方法中。
真正被执行的是类。
override(重写父类方法),覆盖,由子类重新定义继承下来的方法,以改变或延申此方法的行为。
类是对象的蓝图。
受测试类名称+TestDrive
main方法的两种用途:1.测试真正的类;2.启动Java程序

//codegym内容
garbage collector(GC,垃圾回收机制)
**the garbage collector works in parallel with your program.  But it wasn't always so. Garbage collection used to be performed on the same thread as your program. On some schedule (once every few minutes), the garbage collector would check for the presence of unwanted objects in the program. The problem was that the program would hang (not execute) during this check and garbage collection. This mechanism(机制) was later changed, and now the garbage collector runs in the background, not impeding the work of the program itself.**
GC不会统计对象的引用,就像例子中说的三个对象互相引用,程序中其他的与他们无关,若GC统计对象的引用,那就不会收集这三个对象,也就不会释放内存。虽然他们有关联,但是程序中用不到他们,那就是无用的垃圾。
![](https://cdn.codegym.cc/images/article/a8838616-318a-44b1-8bcf-4eb69019799f/800.webp#pic_center)
**Accordingly, in Java, the decision was made to collect garbage based not on reference counting, but on a separation of objects into two types: reachable and unreachable.(可达/不可达) An object is reachable if it is referenced by another reachable object. Thus, we get a "chain of reachability". It starts when the program starts and continues for the duration of the program. The arrow in the figure indicates our program's executable code. The code (for example, the main() method) creates references to objects. These objects can refer to other objects, those objects to still others, and so on. This forms a reference chain.(引用链) If you can trace along to chain from an object to the "root reference" (the one created directly in executable code), then it is considered reachable. Such objects are marked black in the picture.

But an object is unreachable if the object drops out of this chain, i.e. none of the variables in the code currently being executed references it, and it cannot be reached through the "reference chain". In our program, two such objects are marked red.

Note that these "red" objects have references to each other.**
![](https://cdn.codegym.cc/images/article/d6916ebb-571c-4786-83ed-0f15f60730ba/800.webp#pic_center)
![图片反映了垃圾回收机制](https://cdn.codegym.cc/images/article/a24e9f66-458e-4b27-a120-d25f2af013ad/800.webp#pic_center)
Eden中是使用new关键字创建的对象区域,当该区域内存耗尽时,会根据其中垃圾和引用对象的占比采取不同的算法,标记垃圾回收或是标记引用对象转移到生存空间,生存空间又根据对象经历的垃圾回收轮数定了代数,经历一轮就是1代,堆中还有一个长寿命对象的存放地,是经过很多论垃圾回收机制后进入,从生存空间进入长寿对象的存放地。在旧一代满后就会执行完全垃圾回收机制,这个过程涉及多个内存区域。一般来说,它涉及Java机器创建的所有对象。当然,这需要更多的时间和资源。
上面文章节选自[](https://codegym.cc/groups/posts/16-more-about-the-garbage-collector-)讲的是Java的垃圾回收机制。





finalize()方法不会每次都会调用,其是Object类中定义的方法
posted @ 2021-03-25 19:35  吃心王  阅读(119)  评论(0)    收藏  举报