1 2 Previous Next 16 Replies Latest reply: Mar 23, 2010 6:53 AM by 791266 Go to original post RSS
      • 15. Re: RFE: Concise, practical documentation on PhantomReference
        843798
        I have a class which uses PhantomReference to allow resources to be cleaned up. The usage of this class is in line with the ideas in #5 where your application has an object of type A that is what is used as the trafficed object. The A object has inside of it, a reference to a B object that is the resource that needs to be cleaned up as A references are dropped.

        As a simple example, lets say B is a "Socket" object. You'd create a class for managing references to A objects and which cleans up the Socket objects as:
        public class SocketTracker extends ReferenceTracker<A,Socket> {
             public void released( Socket s ) {
                 try {
                     s.close();
                 } catch( Exception ex ) {
                     if( log.isLoggable( Level.FINE ) )
                         log.log( Level.FINE, ex.toString() );
                 }
             }
        }
        Then, you'd just create an instance of this class, and call add( aInstance, aInstance.getSocket() ) as you
        created instances of A to track them and clean up the sockets.

        Now, there are tons of warnings and issues about doing this that have been posted here and elsewhere. One issue that you really need to think about the most is the fact that local-block-only references to instances of A may be queued before the last reference is actually no longer in use. This happens because the GC can not always see local-block-only references that are only seen by Jit'd code where references are in registers. What does this really mean? It means that at best, you can do this for things that are globally referenced, casually. If you really want to do this in local-block-only references, then you must put something akin to
           synchronized( aInstance ){}
        at the end of all code using aInstance so that the reference is not queued prematurely.

        There is discussion of this specific detail on the concurrency-interest mailing list.

        Edited by: greggwon on Mar 22, 2010 10:22 PM
        • 16. Re: RFE: Concise, practical documentation on PhantomReference
          791266
          >

          Hi,

          Please, don't resurrect old threads. The thread was created in 2007. I'm locking it.

          Kaj
          1 2 Previous Next