简体   繁体   中英

Java Memory Management : Do static/non-static objects in various methods retained till end

This may sound very basic, but surely I don't know.

I have a main method main() and from this method I call two methods :->

OneClass {
public static void main(String[] args){
//



  AnotherClass aCObject = new AnotherClass();

   Type1 objectOfType1 = aCObject.method1();

   Type2 objectOfType2 = AnotherClass.method2();

}

}

below methods (may be in same class or other) may be in same class :->

Another Class - :>

public AnotherClass(){

public Type1 method1(){

// do something using maps, arraylists etc
//and return 
}


public static Type2 method2(){

// lots of variables. hashmaps, lists etc
//and return
}


}

Now, from the sample code above, my query is, does JVM retains any of these variables to lead to memory leak. The return type (Type1 and Type2) could be anything (String, Map, List etc ).

Query I am calling method1 and method2 from main method. They perform certain operation and return something. So question is : does JVM destroys variables/objects used in method1 and method2 ? There may be problem of memory leak in method1 and method2 , but is it possible that we have already returned what we wanted from them and now they are candidates for GC ? Or jvm retains memory allocated in case of static method but deletes in case of non-static one.

If the objects returned by method1() and method2() do not contain direct or indirect references to the objects referenced by local variables of those methods, then as soon as the methods return, the local variables go out of scope and the referenced objects are immediately eligible for garbage collection. (That's provided that the methods didn't do anything to cause references to those objects to be stashed somewhere else, such as a static List .) When or if they get collected depends on the machine implementation and the memory demands at run time.

The rules are no different for static and instance methods: as soon as a local variable goes out of scope (eg, the method returns) then the referenced object is eligible for GC unless there is another live reference to the object somewhere else. It also doesn't matter how the method was called (from a static method, an instance method, an initializer, ...).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM