<p>Phantom References serve for post-mortem operations.
The Java specification states that a <strong>phantom referenced object</strong> will not be deallocated until the phantom-reference itself is cleaned.</p>

<p>My question is: What purpose does this feature (object not deallocated) serve?</p>

<p>(The only idea i came up with, is to allow native code to do post-mortem cleanup on the object, but it isn't much convincing).</p>

[{'answer_id': 80847, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 2, 'selected': False, 'text': '<p>Edit, since I\'ve misunderstand the question first:</p>\n\n<p>Quoted from here <a href="http://www.memorymanagement.org/glossary/p.html" rel="nofollow noreferrer">http://www.memorymanagement.org/glossary/p.html</a>:</p>\n\n<blockquote>\n  <p>The Java specification says that the\n  phantom reference is not cleared when\n  the reference object is enqueued, but\n  actually, there\'s no way in the\n  language to tell whether that has been\n  done or not. In some implementations,\n  JNI weak global references are weaker\n  than phantom references, and provide a\n  way to access phantom reachable\n  objects.</p>\n</blockquote>\n\n<p>But I found no other references which would say the same.</p>\n'}, {'answer_id': 80858, 'author': 'Javaxpert', 'author_id': 15241, 'author_profile': 'https://Stackoverflow.com/users/15241', 'pm_score': -1, 'selected': False, 'text': '<p>It can allow you two have phantom caches which are very efficient in memory management.\nSimply put, if you have huge objects that are expensive to create but seldom used, you can use a phantom cache to reference them and be sure they do not take up memory that is more valuable.  If you use regular references you have to be manually make sure there are no references left to the object.  You can argue the same about any object but you dont have to manually manage the references in your phantom cache.  Just have to be carefull to check if they have been collected or not.</p>\n\n<p>Also you can use a framework (i.e. a factory) where references are given as phantom references.  This is useful if the objects are many and short lived (i.e. used and then disposed).  Very handy for clearing memory if you have sloppy programmers that think garbage collection is magical.</p>\n'}, {'answer_id': 80867, 'author': 'Zarkonnen', 'author_id': 15255, 'author_profile': 'https://Stackoverflow.com/users/15255', 'pm_score': 1, 'selected': False, 'text': '<p>I think the idea is to let other objects do extra cleanup above and beyond what the original object does. For example, if the original object cannot be extended to implement some finalization stuff, you can use phantom references.</p>\n\n<p>The bigger problem is that the JVM makes no guarantee that an object will ever be finalized, and I assume by extension no guarantee that phantom references get to do their thing post-finalization.</p>\n'}, {'answer_id': 84075, 'author': 'James A. N. Stauffer', 'author_id': 6770, 'author_profile': 'https://Stackoverflow.com/users/6770', 'pm_score': 1, 'selected': False, 'text': '<blockquote>Phantom references can be used to perform pre-garbage collection actions such as freeing resources. Instead, people usually use the finalize() method for this which is not a good idea. Finalizers have a horrible impact on the performance of the garbage collector and can break data integrity of your application if you\'re not very careful since the "finalizer" is invoked in a random thread, at a random time.<br><br>\n\nIn the constructor of a phantom reference, you specify a ReferenceQueue where the phantom references are enqueued once the referenced objects becomes "phantom reachable". Phantom reachable means unreachable other than through the phantom reference. The initially confusing thing is that although the phantom reference continues to hold the referenced object in a private field (unlike soft or weak references), its getReference() method always returns null. This is so that you cannot make the object strongly reachable again.<br><br>\n\nFrom time to time, you can poll the ReferenceQueue and check if there are any new PhantomReferences whose referenced objects have become phantom reachable. In order to be able to to anything useful, one can for example derive a class from java.lang.ref.PhantomReference that references resources that should be freed before garbage collection. The referenced object is only garbage collected once the phantom reference becomes unreachable itself.</blockquote>\n\n<p><a href="http://www.javalobby.org/java/forums/m91822870.html#91822413" rel="nofollow noreferrer">http://www.javalobby.org/java/forums/m91822870.html#91822413</a></p>\n'}, {'answer_id': 7755030, 'author': 'Ed Staub', 'author_id': 685923, 'author_profile': 'https://Stackoverflow.com/users/685923', 'pm_score': 2, 'selected': True, 'text': '<p>The only good use-case I can think of, that would prevent deallocation, is one where some kind of JNI-implemented asynchronous data source is writing into the referenced object, and must be told to stand down - to stop writing into the object - before the memory is recycled. If prior deallocation were allowed, a simple forgot-to-dispose() bug could result in memory corruption. </p>\n\n<p>This is one of the cases where finalize() would have been used in the past, and probably drove some of its quirks.</p>\n'}, {'answer_id': 42442953, 'author': 'Grwww', 'author_id': 7371705, 'author_profile': 'https://Stackoverflow.com/users/7371705', 'pm_score': 0, 'selected': False, 'text': '<p>This is a perfect solution for APIs which don\'t have a lifecycle management mechanism, but which you are implementing with something which requires explicit lifecycle management.</p>\n\n<p>In particular any sort of API which used to just use objects in memory, but which you\'ve reimplemented using a socket connection or file connection to some other, larger backing store, can use PhantomReference to "close" and cleanup connection information prior to the object being GC\'d and the connection never closed because there was no lifecycle management API interface that you could otherwise use.</p>\n\n<p>Think of moving a simple Map map into a database.  When the map reference is discarded, there is no explicit "close" operation.  Yet, if you had implemented a write through cache, you\'d like to be able to finish any writes and close the socket connection to the your "database".</p>\n\n<p>Below is a class which I use for this kind of stuff.  Note, that References to PhantomReferences must be non-local references to work correctly.  Otherwise, the jit will cause them to be queued prematurely before you exit blocks of code.</p>\n\n<pre>\n\n    import java.lang.ref.PhantomReference;\n    import java.lang.ref.Reference;\n    import java.lang.ref.ReferenceQueue;\n    import java.util.ArrayList;\n    import java.util.List;\n    import java.util.concurrent.ConcurrentHashMap;\n    import java.util.concurrent.atomic.AtomicInteger;\n    import java.util.logging.Level;\n    import java.util.logging.Logger;\n\n    /**\n     * This class provides a way for tracking the loss of reference of one type of\n     * object to allow a secondary reference to be used to perform some cleanup\n     * activity.  The most common use of this is with one object which might\n     * contain or refer to another object that needs some cleanup performed\n     * when the referer is no longer referenced.\n     * <p>\n     * An example might be an object of type Holder, which refers to or uses a\n     * Socket connection.  When the reference is lost, the socket should be\n     * closed.  Thus, an instance might be created as in\n     * <pre>\n     *    ReferenceTracker trker = ReferenceTracker() {\n     *        public void released( Socket s ) {\n     *            try {\n     *                s.close();\n     *            } catch( Exception ex ) {\n     *                log.log( Level.SEVERE, ex.toString(), ex );\n     *            }\n     *        }\n     *  };\n     * </pre>\n     * Somewhere, there might be calls such as the following.\n     * <pre>\n     *        interface Holder {\n     *            public T get();\n     *        }\n     *        class SocketHolder implements Holder {\n     *            Socket s;\n     *            public SocketHolder( Socket sock ) {\n     *                s = sock;\n     *            }\n     *            public Socket get() {\n     *                return s;\n     *            }\n     *        }\n     * </pre>\n     * This defines an implementation of the Holder interface which holds\n     * a reference to Socket objects.  The use of the <code>trker</code>\n     * object, above, might then include the use of a method for creating\n     * the objects and registering the references as shown below.\n     * <pre>\n     *    public SocketHolder connect( String host, int port ) throws IOException {\n     *        Socket s = new Socket( host, port );\n     *        SocketHolder h = new SocketHolder( s );\n     *        trker.trackReference( h, s );\n     *        return h;\n     *    }\n     * </pre>\n     * Software wishing to use a socket connection, and pass it around would\n     * use SocketHolder.get() to reference the Socket instance, in all cases.\n     * then, when all SocketHolder references are dropped, the socket would\n     * be closed by the <code>released(java.net.Socket)</code> method shown\n     * above.\n     *<p>\n     * The {@link ReferenceTracker} class uses a {@link PhantomReference} to the first argument as\n     * the key to a map holding a reference to the second argument.  Thus, when the\n     * key instance is released, the key reference is queued, can be removed from\n     * the queue, and used to remove the value from the map which is then passed to\n     * released().\n     */\n    public abstract class ReferenceTracker {\n        /**\n         * The thread instance that is removing entries from the reference queue, refqueue, as they appear.\n         */\n        private volatile RefQueuePoll poll;\n        /**\n         * The Logger instance used for this instance.  It will include the name as a suffix \n         * if that constructor is used.\n         */\n        private static final Logger log = Logger.getLogger(ReferenceTracker.class.getName());\n        /**\n         * The name indicating which instance this is for logging and other separation of\n         * instances needed.\n         */\n        private final String which;\n\n        /**\n         * Creates a new instance of ReferenceTracker using the passed name to differentiate\n         * the instance in logging and toString() implementation.\n         * @param which The name of this instance for differentiation of multiple instances in logging etc.\n         */\n        public ReferenceTracker( String which  ) {\n            this.which = which;\n        }\n\n        /**\n         * Creates a new instance of ReferenceTracker with no qualifying name.\n         */\n        public ReferenceTracker( ) {\n            this.which = null;\n        }\n\n        /**\n         * Provides access to the name of this instance.\n         * @return The name of this instance.\n         */\n        @Override\n        public String toString() {\n            if( which == null ) {\n                return super.toString()+": ReferenceTracker";\n            }\n            return super.toString()+": ReferenceTracker["+which+"]";\n        }\n\n        /**\n         * Subclasses must implement this method.  It will be called when all references to the\n         * associated holder object are dropped.\n         * @param val The value passed as the second argument to a corresponding call to {@link #trackReference(Object, Object) trackReference(T,K)}\n         */\n        public abstract void released( K val );\n\n        /** The reference queue for references to the holder objects */\n        private final ReferenceQueuerefqueue = new ReferenceQueue();\n        /**\n         * The count of the total number of threads that have been created and then destroyed as entries have\n         * been tracked.  When there are zero tracked references, there is no queue running.\n         */\n        private final AtomicInteger tcnt = new AtomicInteger();\n        private volatile boolean running;\n        /**\n         * A Thread implementation that polls {@link #refqueue} to subsequently call {@link released(K)}\n         * as references to T objects are dropped.\n         */\n        private class RefQueuePoll extends Thread {\n            /**\n             * The thread number associated with this instance.  There might briefly be two instances of\n             * this class that exists in a volatile system.  If that is the case, this value will\n             * be visible in some of the logging to differentiate the active ones.\n             */\n            private final int mycnt;\n            /**\n             * Creates an instance of this class.\n             */\n            public RefQueuePoll() {\n                setDaemon( true );\n                setName( getClass().getName()+": ReferenceTracker ("+which+")" );\n                mycnt = tcnt.incrementAndGet();\n            }\n            /**\n             * This method provides all the activity of performing <code>refqueue.remove()</code>\n             * calls and then calling <code>released(K)</code> to let the application release the\n             * resources needed.\n             */\n            public @Override void run() {\n                try {\n                    doRun();\n                } catch( Throwable ex ) {\n                    log.log( done ? Level.INFO : Level.SEVERE,\n                        ex.toString()+": phantom ref poll thread stopping", ex );\n                } finally {\n                    running = false;\n                }\n            }\n\n            private volatile boolean done = false;\n            private void doRun() {\n                while( !done ) {\n                    Reference ref = null;\n                    try {\n                        running = true;\n                        ref = refqueue.remove();\n                        K ctl;\n                        synchronized( refmap ) {\n                            ctl = refmap.remove( ref );\n                            done = actCnt.decrementAndGet() == 0;\n                            if( log.isLoggable( Level.FINE ) ) {\n                                log.log(Level.FINE, "current act refs={0}, mapsize={1}", new Object[]{actCnt.get(), refmap.size()});\n                            }\n                            if( actCnt.get() != refmap.size() ) {\n                                Throwable ex = new IllegalStateException("count of active references and map size are not in sync");\n                                log.log(Level.SEVERE, ex.toString(), ex);\n                            }\n                        }\n\n                        if( log.isLoggable( Level.FINER ) ) {\n                            log.log(Level.FINER, "reference released for: {0}, dep={1}", new Object[]{ref, ctl});\n                        }\n                        if( ctl != null ) {\n                            try {\n                                released( ctl );\n                                if( log.isLoggable( Level.FINE ) ) {\n                                    log.log(Level.FINE, "dependant object released: {0}", ctl);\n                                }\n                            } catch( RuntimeException ex ) {\n                                log.log( Level.SEVERE, ex.toString(), ex );\n                            }\n                        }\n\n                    } catch( Exception ex ) {\n                        log.log( Level.SEVERE, ex.toString(), ex );\n                    } finally {\n                        if( ref != null ) {\n                            ref.clear();\n                        }\n                    }\n                }\n\n                if( log.isLoggable( Level.FINE ) ) {\n                    log.log(Level.FINE, "poll thread {0} shutdown for {1}", new Object[]{mycnt, this});\n                }\n            }\n        }\n\n        /**\n         * A count of the active references.\n         */\n        private final AtomicInteger actCnt = new AtomicInteger();\n        /**\n         * Map from T References to K objects to be used for the released(K) call\n         */\n        private final ConcurrentHashMap,K>refmap = new ConcurrentHashMap,K>();\n        /**\n         *  Adds a tracked reference.  dep should not refer to ref in any way except possibly\n         *  a WeakReference.  dep is almost always something referred to by ref.\n         * @throws IllegalArgumentException of ref and dep are the same object.\n         * @param dep The dependent object that needs cleanup when ref is no longer referenced.\n         * @param ref the object whose reference is to be tracked\n         */\n        public void trackReference( T ref, K dep ) {\n            if( ref == dep ) {\n                throw new IllegalArgumentException( "Referenced object and dependent object can not be the same" );\n            }\n            PhantomReference p = new PhantomReference( ref, refqueue );\n            synchronized( refmap ) {\n                refmap.put( p, dep );\n                if( actCnt.getAndIncrement() == 0 || running == false ) {\n                    if( actCnt.get() > 0 && running == false ) {\n                        if (log.isLoggable(Level.FINE)) {\n                            log.fine("starting stopped phantom ref polling thread");\n                        }\n                    }\n                    poll = new RefQueuePoll();\n                    poll.start();\n                    if( log.isLoggable( Level.FINE ) ) {\n                        log.log( Level.FINE, "poll thread #{0} created for {1}", new Object[]{tcnt.get(), this});\n                    }\n                }\n            }\n        }\n\n        /**\n         *  This method can be called if the JVM that the tracker is in, is being\n         *  shutdown, or someother context is being shutdown and the objects tracked\n         *  by the tracker should now be released.  This method will result in \n         *  {@link #released(Object) released(K) } being called for each outstanding refernce.\n         */\n        public void shutdown() {\n            Listrem;\n            // Copy the values and clear the map so that released\n            // is only ever called once, incase GC later evicts references\n            synchronized( refmap ) {\n                rem = new ArrayList( refmap.values() );\n                refmap.clear();\n            }\n            for( K dep : rem ) {\n                try {\n                    released( dep );\n                } catch( Exception ex ) {\n                    log.log( Level.SEVERE, ex.toString(), ex );\n                }\n            }\n        }\n    }\n\n</pre>\n'}]
['https://Stackoverflow.com/questions/80690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15100/']