Home > Java > javaTutorial > Will Static Fields Be Garbage Collected When No Longer Referenced?

Will Static Fields Be Garbage Collected When No Longer Referenced?

Patricia Arquette
Release: 2024-12-16 03:44:18
Original
323 people have browsed it

Will Static Fields Be Garbage Collected When No Longer Referenced?

Garbage Collection of Static Fields

A common question arises regarding the fate of static fields when they are no longer referenced. Consider the following utility class intended for program setup:

class MyUtils {
   private static MyObject myObject = new MyObject();
   /*package*/static boolean doStuff(Params... params) {
       // do stuff with myObject and params...
   }
}
Copy after login

Will the myObject field be garbage collected once it is no longer in use, or will it persist throughout the program's execution?

To answer this, we must understand the nature of static variables. Static variables are allocated memory at class loading time and exist for the lifetime of the class. The garbage collector cannot reclaim them as long as the class is loaded.

According to the Java Language Specification (JLS) Section 12.7:

A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector [...] Classes and interfaces loaded by the bootstrap loader may not be unloaded.
Copy after login

Therefore, static variables in loaded classes cannot be garbage collected until the corresponding class loader is itself collected. As bootstrap classes are not unloadable, static variables in those classes will persist indefinitely.

In the case of MyUtils, since it is not loaded by the bootstrap class loader, its static myObject field can be garbage collected once the program no longer requires MyUtils, regardless of whether it is used or not.

The above is the detailed content of Will Static Fields Be Garbage Collected When No Longer Referenced?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template