Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8351374

Improve comment about queue.remove timeout in CleanerImpl.run

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • 25
    • None
    • core-libs
    • None
    • b15

      In CleanerImpl.run there is a call to ReferenceQueue.remove with a timeout. There is a comment describing the timeout as being to avoid a hang due to a race with clear/clean. That comment isn't very informative, as it's very nonobvious what problem is being solved.

      https://github.com/openjdk/jdk/blame/3626ac35b34650dc64938af63ea21f9f4e011fe4/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java#L138-L140

      The problem arises when the Cleaner has become unreachable, GC'ed, and its associated cleanable has run, but there are still registered cleanables for other objects that haven't become unreachable yet. If the non-timeout form of remove is used then the cleaning thread will block there until some of those remaining cleanable object are GC'ed. But if the application cleans all of those cleanables, there won't be any left to get GC'ed and enqueued to wake up the blocked thread. So the thread will never notice that the registered cleanable set is empty and so the thread won't ever exit.

      The timeout allows the thread to periodically check whether there are still registered cleanables or should it exit.

      A different, more prompt approach, is to have the removal of the last registered cleanable post (via Reference.enqueue) a dummy reference object, to wake up the thread. While the timeout has some very minor performance downsides, it is much simpler.

            kbarrett Kim Barrett
            kbarrett Kim Barrett
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: