[JVM] Object death judgment

Brief description

The heap stores almost all object instances in the Java world. Before the garbage collector recycles the heap, the first thing to do is to determine which of these objects are still "alive" and which have "died" ("dead"). "That is, an object that can no longer be used in any way).

Reference counting algorithm

The reference counting algorithm is a garbage collection algorithm used for memory management. Its core idea is to maintain a reference count for each object, indicating how many references point to the object. When the reference count reaches zero, it means that the object is no longer pointed to by any reference and the memory can be safely reclaimed.

The main features and advantages of reference counting algorithms include:

  1. Simple : The reference counting algorithm is very simple and intuitive, every time a reference to an object changes, the reference count increases or decreases accordingly.
  2. Real-time : Since the reference count is maintained in real time, once the reference count reaches zero, the object can be recycled immediately without waiting for the garbage collector to run.
  3. Minimize pause time : Reference counting algorithms usually do not need to perform global garbage collection operations, so they do not cause long pauses caused by large-scale memory recycling.

However, the reference counting algorithm also has some obvious disadvantages:

  1. Circular reference problem : The reference counting algorithm cannot handle circular reference situations. If two or more objects reference each other, their reference counts will never reach zero, even if they are no longer used by the program. This can cause memory leaks.
  2. Performance overhead : Each time a reference changes, the reference count needs to be incremented or decremented, which adds additional performance overhead. Additionally, additional memory is required to store reference counts.
  3. Not suitable for multi-threaded environments : In multi-threaded environments, reference counting requires atomic operations to ensure counting accuracy. This introduces additional overhead and complexity.

All things considered, reference counting algorithms can be an effective garbage collection method in simple scenarios, but are generally not the first choice in complex applications. Many modern programming languages ​​and runtime environments use reference counting-based recycling algorithms combined with other algorithms (such as mark-sweep, mark-complement, etc.) to overcome the shortcomings of reference counting algorithms and improve the efficiency and reliability of memory management.

Reachability analysis algorithm

The basic idea of ​​this algorithm is to use a series of root objects called "GC Roots" as the starting node set. Starting from these nodes, search downward according to the reference relationship. The path traveled by the search process is called the "reference chain" ( Reference Chain), if there is no reference chain connecting an object to GC Roots, or in graph theory terms, when the object is unreachable from GC Roots, it proves that the object can no longer be used.

Although the objects object 5, object 6, and object 7 in the figure below are related to each other, they are not reachable from GC Roots, so they will be judged as recyclable objects.

image-20230903223251580

In the Java technology system, the objects that can be used as GC Roots include the following:

  • Objects referenced in the virtual machine stack (local variable table in the stack frame), such as parameters, local variables, temporary variables, etc. used in the method stack called by each thread.

  • Objects referenced by class static attributes in the method area, such as reference type static variables of Java classes.

  • Objects referenced by constants in the method area, such as references in the string constant pool (String Table).

  • Objects referenced by JNI (commonly known as Native methods) in the native method stack.

  • References within the Java virtual machine, such as Class objects corresponding to basic data types, some resident exception objects (such as NullPointExcepiton, OutOfMemoryError), etc., as well as the system class loader.

  • All objects held by synchronized locks (synchronized keyword). ·JMXBean that reflects the internal situation of the Java virtual machine, callbacks registered in JVMTI, local code cache, etc.

In addition to these fixed GC Roots collections, other objects can be added "temporarily" depending on the garbage collector selected by the user and the memory area currently recycled, which together form a complete GC Roots collection.

The advantage of the reachability analysis algorithm is that it can accurately identify objects that are no longer referenced by the program , so it can effectively reclaim memory and avoid memory leaks. However, its disadvantage is that it needs to traverse the entire object graph , so it may consume more time and computing resources when there are a large number of objects and complex reference relationships. Therefore, modern garbage collectors often combine different collection algorithms to optimize performance.

4 types of object references

After JDK version 1.2, Java expanded the concept of references and divided references into four types: Strongly Reference, Soft Reference, Weak Reference and Phantom Reference. , these four citation strengths gradually weaken in sequence.

There are four different types of references, which are:

  1. Strong Reference :
    • Strong references are the most common type of reference.
    • When an object has a strong reference, the garbage collector will not reclaim the object, even when there is insufficient memory.
    • The object will be recycled only when all strong references to the object are invalid.
  2. Soft Reference :
    • Soft references are used to describe objects that are useful but not necessary.
    • When there is insufficient memory, the garbage collector may reclaim objects pointed to by soft references, but will not reclaim them when there is enough memory.
    • java.lang.ref.SoftReferenceSoft references can be created through classes.
  3. Weak Reference :
    • Weak references are used to describe non-essential objects and are often used for caching.
    • The object pointed to by a weak reference will be recycled during the next garbage collection, regardless of whether there is enough memory.
    • java.lang.ref.WeakReferenceWeak references can be created through classes.
  4. Phantom Reference :
    • Virtual references are the weakest reference type and are often used to track the status of objects being garbage collected.
    • Virtual references cannot access the object's data or methods through it. It is mainly used to receive a system notification before the object is recycled.
    • java.lang.ref.PhantomReferenceVirtual references can be created through classes.

These different types of references allow developers to more flexibly control the object's life cycle. For example, soft references and weak references are often used in caches to allow objects in the cache to be recycled when memory is low, thereby avoiding memory overflows. Virtual references can be used to perform some cleanup operations or record when an object is garbage collected. The appropriate reference type needs to be selected based on specific needs.

finalize() method

finalize()Method is a special method in Java that belongs to java.lang.Objecta class and is used to perform some cleanup and resource release operations before the object is garbage collected. Although it exists, starting from Java 9, it has been marked as "deprecated" because it has some problems and instability and is not recommended for use in new code.

Here are finalize()some important information and notes about the method:

  1. Signature of finalize() method :

    protected void finalize() throws Throwable {
          
          
        // 执行清理和资源释放操作
    }
    

    finalize()The access modifier of a method is protected, indicating that only methods in the same class or its subclasses can call it.

  2. Execution timing of finalize() method :

    • finalize()The execution timing of the method is uncertain, and different garbage collectors execute it under different circumstances. Some garbage collectors may not perform it at all.
    • Before an object is garbage collected, the garbage collector will first call finalize()the method, and then the object will be recycled. However, there is no guarantee finalize()that the method will be executed, so it should not be relied on for resource release or cleanup operations.
  3. Problems with finalize() method :

    • finalize()The execution timing of the method is uncertain, which may cause delays in resource release.
    • During the execution finalize()of the method, the object is still in an "alive" state, which may cause some concurrency issues.
    • Due to instability and performance issues, Java 9 introduced a more advanced garbage collection mechanism, gradually reducing finalize()dependence on methods.
  4. Suggested alternative :

    • For resource release, structures such as try-with-resourcesor finallyblocks should be used to ensure timely release of resources.
    • For object life cycle management, more reliable methods should be used, such as weak references, virtual references, etc., rather than relying on finalize()methods.

In short, finalize()although the method exists, it is no longer recommended because it has some problems and uncertainties that may lead to code instability and performance issues. In modern Java programming, more reliable and controllable ways should be used to manage object life cycles and resource release.

Note: The finalize() method of any object will only be automatically called once by the system.

Recycling method area

The method area (Method Area) of the Java virtual machine is usually not garbage collected by the garbage collector like the heap memory. The method area is mainly used to store the structural information, constants, static variables and bytecode of the class. These data will be loaded and used throughout the life cycle of the program and will not be recycled due to the accessibility of the object.

However, although the method area is generally not garbage collected, in some cases some data in the method area may be recycled or unloaded:

  1. Useless class unloading : When a class is no longer referenced and is no longer loaded by any active class loader, the class may be unloaded and its related information in the method area will also be recycled. This process usually occurs when the class loader is recycled, such as when the web application is reloaded.

  2. Recycling of useless constants in the constant pool : At runtime, some constants in the constant pool, especially string constants, may be recycled because they have no reference.

  3. Optimization technology : Some Java virtual machine implementations use optimization technology for data in the method area, which can perform hot replacement (HotSwap) or dynamic generation of classes at runtime. These technologies may cause some data in the method area to be recycled or replaced. .

It should be noted that the recycling and memory management of the method area are different from the garbage collection of the heap memory. Usually, the memory management and recycling of the method area is taken care of by the Java virtual machine itself without developer intervention. Garbage collection of heap memory usually involves developers manually managing and object reference relationships in the code. In Java 8 and later versions, the method area is replaced by the metadata area (Metaspace), and its management method is also different, including a more flexible memory management mechanism.

In scenarios where reflection, dynamic proxy, CGLib and other bytecode frameworks are extensively used, and JSPs and frequently customized class loaders such as OSGi are dynamically generated, the Java virtual machine is usually required to have type unloading capabilities to ensure that methods are not modified. area causing excessive memory pressure.

To sum up, the method area usually does not need to be explicitly recycled, but is automatically managed by the Java virtual machine. What developers need to focus on is the life cycle and memory management of the object, and the management of the method area usually does not require additional intervention.

Guess you like

Origin blog.csdn.net/m0_51545690/article/details/132657420