What are the java judgment methods?
This article mainly explains "what are the java judgment methods", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let Xiaobian take you to learn "what are the java judgment methods"!
. citation counting
This method maintains a counter at the head of the object, incrementing the counter when there is a reference to the object, and decrementing the counter when there is no reference to the object. So, when counter equals zero, the virtual machine assumes that the object can be recycled. It seems reasonable, but there is a fatal problem with this approach:
As shown in the figure above, there is an external reference to object A, which holds object B, which also holds an object C, which in turn holds object A. If the reference r to object A expires, GC can never reclaim the above three objects according to the reference counting method. So based on the huge flaw above that memory leaks exist, Java virtual machines (which should be most virtual machines) do not reclaim memory in this way.
. reachability analysis algorithm
Java uses this method as a way to determine whether an object can be recycled. The virtual machine will first define some objects as GC Roots, starting from GC Roots and looking down the chain of references. If an object cannot be found through GC Roots, the virtual machine considers that the object can be recycled. Let's take an example, as shown below:
When object D no longer references object A, GC will reclaim the memory occupied by ABC, even though A, B, and C still hold references to each other. Then there is the question, what kind of objects can be considered GC Roots?
Reference objects in virtual machine stack (local variable table in stack frame)
Objects referenced by static attributes of classes in the methods section
Objects referenced by constants in the method section
Objects referenced by JNI (Native Method) in Native Method Stack
At this point, I believe that everyone has a deeper understanding of "java judgment methods," may wish to actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!