ReferenceDemo.java

Download ReferenceDemo.java source file

/** Weak and soft reference demo.
 *
 * The first program reads data from a file.  Since the data may be requested
 * again later, we save it using a soft reference.  The GC may (or may not)
 * free the object if low on space, often removing the older objects first.
 * This means you can use soft references to make a "cache": save something
 * in RAM in case it is needed again later, but allow the GC to reclaim it
 * if running low on space.
 *
 * Weak references are useful for indexes to objects.  If the objects are
 * otherwise freed, you don't want the index to force the JVM to keep the
 * object in RAM.  If some object only has weak references to it the GC will
 * free it up (as if there were no references to it).  This sort of index is
 * so common there is a WeakHashMap collection with weakly referenced keys;
 * An entry in a WeakHashMap will automatically be removed when its key is
 * no longer in ordinary use.  (Presumably this will free the value as well.)
 * the second program shows a simple way to track which logged in users are
 * in some chat room.  If the user logs out ordinarily you would need to add
 * code to find which room(s) that user was in and remove them from it (them).
 * This is a good use for weak references.

// Written 2/2001 by Wayne Pollock, Tampa Florida USA.
// (Adapted from "The Java Programming Language" 3rd Ed. by Ken Arnold et. al.)

import java.lang.ref.*;
import java.io.File;

class DataCache
{
   private File lastFile;  // This should probably be soft too!
   private SoftReference lastData;

   byte[] readFromFile ( File file )
   {
      byte [] data;

      // Check if we already have the right data saved in RAM:
      if ( file.equals( lastFile )
      {
         data = (byte[]) lastData.get();
         // Data may have been garbage collected, so check:
         if ( data != null )  return data;
      }

      // Don't have data, so read and save it in cache:
      data = readBytesFromFile( file );
      lastFile = file;
      lastData = new SoftReference( data );
      return data;
   }
}

/*********************************************************/

class Person
{
   String name;
   UserID id;
   ...
   UserID getID () { return id; }
}

class ChatServer
{
   List<UserID> loggedInusers = new ArrayList<UserID>();
   ...

   void login ()
   {
      ...
      Person p = new Person( ... );
      loggedInUsers.add( p.getID() );
   }

   ...

   void logout ( UserID id )
   {
      ...
      loggedInUsers.remove( id );  // Deletes from chatrooms too!
   }

}

class ChatRoom
{
   WeakHashMap<UserID, Person> users = new WeakHashMap<UserID, Person>();

   ...

   public void userEntersRoom ( UserID id, Person user )
   {
      users.add( id, user );
      ...
   }

   public void listUsersInRoom ()
   {
      for ( UserID id : users.keySet() )
         System.out.println( users.get(id) );
   }
}