I'm wondering how garbage collection works when you have a class with reflection used to get some field values. How is the JVM aware that the values references by these fields are accessible and so not eligible for garbage collection at the present moment, when formal language syntax is not used to access them?
A small snippet indicating the issue (although reflection has been over-emphasised here):
/**
*
*/
import java.lang.reflect.Field;
public class B {
protected B previous = null, next = null;
/**
*
*/
public B(B from) {
this.previous = from;
}
public void transition(B to) {
this.next = to;
}
public B next() {
try {
Field f = getClass().getField("next");
f.setAccessible(true);
try {
return (B)f.get(this);
} finally {
f.setAccessible(false);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public B previous() {
try {
Field f = getClass().getField("previous");
f.setAccessible(true);
try {
return (B)f.get(this);
} finally {
f.setAccessible(false);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
Cheers,
Chris
Garbage collection (GC) is a memory recovery feature built into programming languages such as C# and Java. A GC-enabled programming language includes one or more garbage collectors (GC engines) that automatically free up memory space that has been allocated to objects no longer needed by the program.
Garbage collection (GC) is a dynamic approach to automatic memory management and heap allocation that processes and identifies dead memory blocks and reallocates storage for reuse. The primary purpose of garbage collection is to reduce memory leaks.
Garbage collection allows the "free" part of the operation to happen in batches, and at times when the application is otherwise relatively idle. In other words, a highly-efficient garbage collector has the potential to be faster (not that we're quite that far yet, but they are improving all the time).
If you are accessing the fields of an instance, then you will still need a reference to that instance. There would be nothing abnormal about GC for that case.
To access a field of an object you must have a reference to that object. If you access it via reflections or directly it doesn't make any difference to whether you have a strong reference to the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With