简体   繁体   English

如何在Java中编写自己的垃圾收集器?

[英]How to write own garbage collector in java?

This is most generally asked question in interview. 这是面试中最常见的问题。 I do not want to use Java garbage collector. 我不想使用Java垃圾收集器。 How we can implement own garbage-collector functionality. 我们如何实现自己的垃圾收集器功能。 Does anyone have solution for this question ? 有人对此问题有解决方案吗?

From a practical perspective, this is not something that can really be done as the GC is an internal (and integral) part of the JVM. 从实际的角度来看,这并不是真正可以完成的事情,因为GC是JVM的内部(和组成部分)。 From an academic standpoint, you need to have a deep understanding of how the JVM allocates memory. 从学术角度来看,您需要对JVM如何分配内存有深刻的了解。 Most garbage collection algorithms work by starting at some set of known roots. 大多数垃圾收集算法都是从一组已知的根开始的。 From each root, it traverses memory looking for any objects that no longer have any references to them. 从每个根开始,它遍历内存以查找不再有任何引用的对象。 Those objects that don't have references are considered garbage and have the memory they occupy deallocated. 那些没有引用的对象被视为垃圾,并释放了它们占用的内存。 Any remaining objects are still live and are moved around in memory to compact the memory usage and reduce fragmentation. 所有剩余的对象仍然有效,并在内存中四处移动以压缩内存使用量并减少碎片。

This is probably not precisely how the JVM GC works, but it illustrates the basic concepts. 这可能不完全是JVM GC的工作方式,但是它说明了基本概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM