why don't most JVM gcs use refcounts?

前端 未结 2 1030
生来不讨喜
生来不讨喜 2021-01-11 23:18

Why don\'t they need them, and if someone decided to implement a VM that used them, what problems might they face?

相关标签:
2条回答
  • 2021-01-11 23:58

    Reference counting is subject to memory leaks due to cyclical references. Imagine you have a simple "node" object which has a reference to another node, and suppose you set its reference to itself. The reference count for that object will always be 1 even if there is no handle to it from a global or stack variable so it will never be garbage collected and is leaked memory. This is a trivial example but any cyclical reference will have the same problem.

    Of course, cyclical references can be detected but presumably the overhead of doing so adds enough complexity that other GC methods are more attractive.

    0 讨论(0)
  • 2021-01-12 00:05

    1. Counting references must be done outside the object.
    2. Counting references is slow. Even slower to deal w/ cyclic references but that's not impossible. Still slow.
    3. Counting references is actually very slow since it must use CAS + loop
    4. Not-Counting references is easier to implement and it's faster, esp. with some OS memory page tricks.
    5. Reference counting can be removed altogether by escape analysis, provided the object doesn't escape.

    0 讨论(0)
提交回复
热议问题