java垃圾回收
Garbage Collection
The java virtual machine(JVM) that runs your program uses hideden data structures to manage memory.
Roots and Reachability
An object your program mignt use again: live, opposite is garbage-objects your program cannot reference again
Root: any reference your proram can access. Primitive variable are not roots.
- local variables on stack
- class variable(static variable)
Object is live(i.e. reachable from root) if it is:
- referenced by a root
- referenced by another live root(ListNode in a live List)
Garbage Collector run DFS from root to find live object.
Every object has a “visited” tag, invisible to your program.
Memory Addresses
Memory is array of bytes with address.
Declare local variable –> naming a variable location.(Java picks the address)
Memory address == Pointers
Mark & Sweep Garbarge Collection
2 phase:
- Mark phase: Do a DFS from every root; marks all live objects
- Sweep phase: Pass over all objects in the memory. Garbage is reclaimed.
Jvm data structrues keep track of free and allocated memory(最简单可以想象成LinkedList), 这种数据结构帮助我们allocate新的变量或者删除掉garbage变量。 Jvm运行一段时间会停下来进行Mark and Sweep。
问题: Fragmentation: tendency of free memory to get broken up into small pieces. Unable to allocate a large object despite lots of free memory
解决方法: Compaction: A compacting garbage collector moves objects during sweep phase.
Campaction会导致很多变量移动,也就是reference的移动,但其实java中由于reference的特殊设计,使得减少大量的操作。同时refernce的移动也会造成本身的fragmentation,但由于reference的大小都是一样的,所以并不会造成像变量一样插不进去的问题,所以是无所谓的。
Copying Garbage Collection
Faster than mark&sweep because only one phase.
Mwmory is divided into 2 spaces, old space and new space.
Find live objects by DFS. When it encounter live object in old space, it immediately moves it to new space. Campaction included.
Next time, new space is relabeled old space, old space is relabeled new space
问题: 只能使用一般的memeory
优点: 比mark&sweep快
Generational Garbage Collection
Most objects have short lifetime; a few live very long.
A generational collection has 2 or more generations.
- can be different sizes.
- can change size.
Generational Garbage集合了以上两种GC的优点。
Example(Sun 1.3 JVM):
Minor collections: frequent;only affect young generations.
Major collections: Cover all objects.
Special tables of references from old objects to young is added to the roots for minor collections.(由于在minor collection的时候,我们只检索年轻代,但可能会存在一些年轻代被年老代所reference,这个时候他们不应该回收,但我们没有对年老代进行DFS。解决方式是用一个table记录。)