Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java garbage-collection affect methods?

My AP Computer Science teacher tells me not to use static methods because Java garbage collection only affects non-static methods, and therefore static methods that are no longer used will take up extra memory. I'm almost positive that GC should never affect any methods, only objects, but I wanted to be sure before I say anything. So does GC have anything to do with methods?

like image 207
Gregorio246 Avatar asked Dec 27 '22 17:12

Gregorio246


2 Answers

use static methods because Java garbage collection only affects non-static methods, and therefore static methods that are no longer used will take up extra memory.

I think you miss understood what he/she said. A method is only unloaded when its ClassLoader is unloaded, in most Java SE programs, that is never.

like image 45
Peter Lawrey Avatar answered Dec 29 '22 05:12

Peter Lawrey


Assuming she really said methods and not fields then your teacher is wrong on this occasion. As you say, garbage collection is the process of reclaiming memory from objects that have been allocated, the scope of the method that allocated them is irrelevant.

As a side note, static fields are a different matter. Holding objects in a static field (usually) does prevent the garbage collector doing its thing as the class will always hold a reference to it and so it won't be eligible for collection.

like image 122
Paolo Avatar answered Dec 29 '22 07:12

Paolo