[concurrency-interest] Fences.keepAlive

Doug Lea dl at cs.oswego.edu
Wed Jan 14 09:20:49 EST 2009

[Same cross-post conventions as the last one.]

As another make-good for a long-standing problem, the
Fences class should include what amounts to a fence with
respect to the garbage collector. This addresses a problem that
Hans Boehm has written and talked about for years.
(Google finds his JavaOne 2005 slides at

This turns out not to be expressible using other kinds of
fences. It tells the compiler/runtime that the ref in
question must be considered as being used even if nothing in
the program itself indicates it. (The suggested JVM implementation
of this is an "opaque fence" that bypasses/evades any
mechanics or optimizations that might cause ref to vanish.)

Here's a first pass at javadoc/spec. Comments welcome.

      * Ensures that object referenced by the given reference is not
      * reclaimable by garbage collection until after the invocation of
      * this method. Among other related usages, this method may assist
      * efforts to ensure that finalization associated with garbage
      * collection does not occur before the finalized resources have
      * even been established.  For example:
      * <pre>
      * class Resource {
      *   static NativeResource nativeResourceArray = ...
      *   static void registerInArray(int index) { ... }
      *   int myIndex;
      *   void setup() {
      *      int i = myIndex;
      *      registerInArray(i);
      *      keepAlive(this);
      *   }
      *   Resource(...) {
      *     myIndex = ...
      *     setup();
      *   }
      * }
      * </pre>
      * @param ref the reference
     public static <T> keepAlive(T ref);

More information about the Concurrency-interest mailing list