Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GC guarantee that cleared References are enqueued to ReferenceQueue in topological order?

Say there are two objects, A and B, and there is a pointer A.x --> B, and we create, say, WeakReferences to both A and B, with an associated ReferenceQueue.

Assume that both A and B become unreachable. Intuitively B cannot be considered unreachable before A is. In such a case, do we somehow get a guarantee that the respective references will be enqueued in the intuitive (topological when there are no cycles) order in the ReferenceQueue? I.e. ref(A) before ref(B). I don't know - what if the GC marked a bunch of objects as unreachable, and then enqueued them in no particular order?

I was reviewing Finalizer.java of guava, seeing this snippet:

private void cleanUp(Reference<?> reference) throws ShutDown {
  ...
  if (reference == frqReference) {
    /*
     * The client no longer has a reference to the
     * FinalizableReferenceQueue. We can stop.
     */
    throw new ShutDown();
  }

frqReference is a PhantomReference to the used ReferenceQueue, so if this is GC'ed, no Finalizable{Weak, Soft, Phantom}References can be alive, since they reference the queue. So they have to be GC'ed before the queue itself can be GC'ed - but still, do we get the guarantee that these references will be enqueued to the ReferenceQueue at the order they get "garbage collected" (as if they get GC'ed one by one)? The code implies that there is some kind of guarantee, otherwise unprocessed references could theoretically remain in the queue.

Thanks

like image 496
Dimitris Andreou Avatar asked Feb 27 '23 08:02

Dimitris Andreou


1 Answers

I'm pretty sure that the answer is no.

The JVM spec says this about finalizer methods:

The Java virtual machine imposes no ordering on finalize method calls. Finalizers may be called in any order or even concurrently. (JVM spec 2.17.7)

From this I infer that there are no guarantees that references are queued in topological order.

like image 180
Stephen C Avatar answered Apr 28 '23 06:04

Stephen C