Does the garbage collector use Java methods?

My AP Computer Science teacher tells me not to use static methods because Java garbage collection only affects non-static methods, so static methods that are no longer used take up extra memory. I am pretty sure that the GC should never affect any methods, only objects, but I wanted to be sure before saying anything. So, does GC have anything to do with methods?

+4
source share
3 answers

Assuming she really said methods, not fields, then your teacher is mistaken about this. As you say, garbage collection is the process of recovering memory from objects that have been allocated, the amount of the allocated method does not matter.

As a side note, static fields are another matter. Holding objects in a static field (usually) does not allow the garbage collector to perform its task, since the class will always refer to it, and therefore it will not have the right to collect it.

+8
source

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

I think you missed the understanding of what he said. A method is only unloaded when its ClassLoader is unloaded, in most Java SE programs that never run.

+1
source

I think your teacher is wrong. Ask him / her if he believes that methods are also copied when cloning objects? If he / she says yes, then he / she is really wrong.

Methods are code, and code is static, i.e. it exists in one instance all the time the class exists.

+1
source

Source: https://habr.com/ru/post/1434488/


All Articles