I get the gist of reference objects in Java, and the basic differences between soft, weak, and phantom reference objects.
However, I don't fully understand the following points from the API docs
From the API doc for WeakReference<T>:
"Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed."
Now, the terms in bold haven't been explained anywhere in the API docs, so I wonder what they precisely mean, especially in relation to the more or less deprecated
Object.finalize()
method's notion of finalization.From the API doc for Reference<T>:
public void clear()
: "This method is invoked only by Java code; when the garbage collector clears references it does so directly, without invoking this method."public boolean enqueue()
: "This method is invoked only by Java code; when the garbage collector enqueues references it does so directly, without invoking this method."Again, I don't know what is meant by "Java code" in above 2 quotes: The JVM internal code to which I have no access? Or, the JDK code to which I have readonly/browsing access? Or, the end-user's own Java code?
The "directly, without invoking this method" part tells me that JVM has no need to call these methods. On the other hand, the "only by Java code" part tells me that it is not the end-user's Java code but rather the JVM's (if it meant end-user code, then we'd be finding this phrase littered in all of the API doc for almost every method of every Java class!). So which interpretation is right and who can call this function?
These are all stages in the Garbage Collection process. Objects first get marked as finalizable to say that there are no strong references to them. Then finalize() is called and they are marked as finalized, and then finally the memory is reclaimed.
This is saying that when you as a programmer decide to clear a reference then the
clear()
method is used to do that, however if you were to subclassWeakReference
and override theclear
method you would NOT see the JVM calling that method when the object was removed.The quote for
enqueue
is essentially saying the same thing. It is a warning that you cannot interact with the workings of the GC by overriding these methods.