Java
javaTutorial
Memory footprint and life cycle analysis of object instances created by Java static methods
Memory footprint and life cycle analysis of object instances created by Java static methods

This article takes an in-depth look at the memory behavior and life cycle of static methods in Java when creating object instances. The core idea is that objects created by static methods are not "static instances". They are stored on the heap like ordinary objects and follow the same garbage collection rules. The article clarifies the relationship between static methods, class loading, and object reachability, and points out that the object creation mechanism (such as the builder pattern) itself does not affect its memory footprint or garbage collection eligibility. The key lies in the reference reachability of the object.
Introduction: Common misunderstandings between static methods and object instances
In Java programming, static methods are widely used in tool classes, factory methods and singleton patterns because they can be called without relying on object instances. However, when static methods are used to create and return object instances, developers often have questions about the memory footprint, life cycle, and whether they have "static" properties. Especially in specific scenarios like the singleton pattern, static methods are often associated with the uniqueness of the object, which makes it easy to create conceptual confusion when using static methods to create multiple instances in other scenarios.
For example, consider the following Java code snippet, where the RandomSumBuilder class contains a static add() method that creates and returns an instance of RandomSumBuilder:
public class Service {
public void doSomething() {
for (int i = 0; i aList = new ArrayList();
public RandomSumBuilder() { }
public static RandomSumBuilder add() {
RandomSumBuilder randomSumBuilder = new RandomSumBuilder();
randomSumBuilder.aList.add(new Random().nextInt(11));
return randomSumBuilder;
}
public int build() {
return aList.stream()
.reduce(Integer::sum)
.orElse(0);
}
}
In this mode, RandomSumBuilder.add() is called frequently to create objects, which raises a series of questions about the memory behavior of these objects, such as whether they are "static instances", whether they will be garbage collected, and what impact they have on the class loader. This article will analyze these issues in depth and clarify related concepts.
Are objects created by static methods "static"?
This is a common misunderstanding, and the answer is: there is no such thing as a "static instance".
In Java, the "static" modifier can be applied to class members (fields and methods) to indicate that they belong to the class itself, rather than to any specific instance of the class.
- Static variable : Indicates that the variable belongs to the class, all instances share the same copy of the variable, and can be accessed without creating an object.
- Static method : Indicates that the method belongs to the class and can be called without creating an object.
However, when a static method creates an object through the new keyword, the created object itself is an ordinary heap object . It is essentially no different from any other object created through a constructor or non-static factory method. It has its own memory space to store the values of its non-static fields.
For example, in the RandomSumBuilder.add() method above:
public static RandomSumBuilder add() {
RandomSumBuilder randomSumBuilder = new RandomSumBuilder(); // An ordinary heap object is created here randomSumBuilder.aList.add(new Random().nextInt(11));
return randomSumBuilder;
}
Each time RandomSumBuilder.add() is called, a brand new RandomSumBuilder instance is created on the heap. These instances are independent and have their own aList fields. They do not possess any "static" properties and cannot be considered "static instances". If a static variable refers to an object, then the variable is static, but the object it refers to is still an ordinary heap object.
Object life cycle and garbage collection
The life cycle and garbage collection behavior of objects created by static methods are exactly the same as ordinary objects. Whether they will be collected by the Garbage Collector (GC) depends entirely on whether they are still reachable .
In Java, an object is reachable, which means that there is at least one reference to it in the program, and this reference chain can be traced back to GC Roots (such as local variables, static fields, active threads, etc. in the executing method stack). If an object is no longer held by any reachable reference, it becomes unreachable and thus becomes a candidate for garbage collection.
Back to the doSomething() method of the Service class:
System.out.println("Random sum : " RandomSumBuilder.add().build());
In this line of code:
- RandomSumBuilder.add() is called, creating a new RandomSumBuilder instance.
- This newly created instance immediately calls the build() method.
- After the build() method is executed, its return value (an int) is printed by System.out.println().
- At this point, the only reference to the RandomSumBuilder instance (the local reference returned by the RandomSumBuilder.add() method) has lost scope.
Therefore, at the end of each loop iteration, the previous RandomSumBuilder instance no longer has any reachable references and it immediately becomes a candidate for garbage collection. Even if the loop is executed 1000 times, it will not cause 1000 RandomSumBuilder instances to reside in memory for a long time. The garbage collector will clean up these no longer used objects at the appropriate time and release the memory they occupy.
Independence of class loading mechanism and instance creation
Another common question is whether frequently creating instances through static methods puts unnecessary burden on the class loader. The answer is: no .
Class Loading and object instance creation are two completely different processes:
- Class loading : When the JVM encounters a class for the first time (for example, when an instance of the class is created for the first time, or a static member of the class is accessed for the first time), it loads the bytecode file (.class) of the class into memory through the class loader, and performs linking (verification, preparation, parsing) and initialization. This process usually only occurs once for a given class loader instance. Once a class is loaded and initialized, its bytecode structures and static members are already in memory.
- Object instance creation : When using the new keyword to create an object, the JVM allocates space for the new object in heap memory and calls its constructor for initialization. This process is a runtime operation and has nothing to do with the class loader . No matter how many instances are created, the class itself is never reloaded.
Therefore, even if instances of RandomSumBuilder are created frequently through static methods, the RandomSumBuilder class will only be loaded once. The class loader does not duplicate work based on the number of instance creations.
Considerations for the Builder Pattern
One might ask, would the memory behavior be any different if the object was created using the classic builder pattern (for example, implemented through a nested class)?
The answer is: From the perspective of object memory usage and garbage collection, there is no essential difference.
The builder pattern is a design pattern that aims to solve the problem of too many constructor parameters and poor readability, or to provide more flexible steps when building complex objects. It usually involves an inner class (which can be static or non-static) that acts as a builder, responsible for setting the properties of the object step by step, and finally returning the final object instance through the build() method.
For example, a typical builder pattern might look like this:
public class Product {
private final String partA;
private final int partB;
private Product(Builder builder) {
this.partA = builder.partA;
this.partB = builder.partB;
}
public static class Builder { // Static nested class private String partA;
private int partB;
public Builder withPartA(String partA) {
this.partA = partA;
return this;
}
public Builder withPartB(int partB) {
this.partB = partB;
return this;
}
public Product build() {
return new Product(this);
}
}
// Getter methods
}
//Usage Product product = new Product.Builder()
.withPartA("ValueA")
.withPartB(123)
.build();
Regardless of whether the object is created through a static factory method (such as RandomSumBuilder.add()), a direct constructor, or the builder pattern, the resulting object instance is an ordinary heap object. Their memory footprint depends on the number and types of their fields, and their eligibility for garbage collection depends on their reference reachability. The strength of the builder pattern lies in its design and maintainability rather than in changing the object's underlying memory behavior.
Summary and best practices
Through the above analysis, we can draw the following key conclusions:
- There is no "static instance" : objects created by static methods are ordinary heap objects, and they do not have any "static" characteristics. Static modifiers act on class members, not object instances.
- Garbage collection is based on reachability : objects created by static methods, like any other object, become candidates for garbage collection as soon as they are no longer held by any reachable reference. Frequent creation of short-lived objects does not lead to memory leaks, as long as these objects become unreachable in time.
- Separation of class loading and instance creation : Class loading usually occurs only once, while object instance creation is an independent runtime operation and does not result in repeated class loading work.
- The creation mechanism does not affect memory behavior : Whether it is a static factory method, a constructor, or the builder pattern, the mechanism of object creation itself does not affect the object's memory footprint or its eligibility for garbage collection. The key lies in how references to an object are managed after it is created, and how reachable it is throughout the program's life cycle.
Best practices :
- Clearly distinguish concepts : When thinking about memory and object life cycles, it is important to distinguish between the concepts of "class" and "object", "static variables" and "object instances".
- Pay attention to reference reachability : The core of understanding garbage collection is "reachability". Ensuring that objects no longer needed can become unreachable in a timely manner is key to avoiding memory leaks.
- Choose the appropriate creation pattern : Choose the appropriate creation pattern (such as factory method, builder pattern, singleton pattern, etc.) based on business needs and design considerations, not based on a wrong understanding of "static" properties. The builder pattern can significantly improve the readability and maintainability of code when constructing complex objects.
Understanding these basic principles is crucial to writing efficient and robust Java code.
The above is the detailed content of Memory footprint and life cycle analysis of object instances created by Java static methods. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20522
7
13634
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.
Complete tutorial on reading data from file and initializing two-dimensional array in Java
Mar 09, 2026 pm 09:18 PM
This article explains in detail how to load an integer sequence in an external text file into a Java two-dimensional array according to a specified row and column structure (such as 2500×100), avoiding manual assignment or index out-of-bounds, and ensuring accurate data order and robust and reusable code.
A concise method in Java to compare whether four byte values are equal and non-zero
Mar 09, 2026 pm 09:40 PM
This article introduces several professional solutions for efficiently and safely comparing multiple byte type return values (such as getPlayer()) in Java to see if they are all equal and non-zero. We recommend two methods, StreamAPI and logical expansion, to avoid Boolean and byte mis-comparison errors.





