/home/wpollock1/public_html/AJava/GenericRefDemo.java
// Generic Class, SoftReference, and WeakReference Demo
// This class creates a generic class Cache that uses soft references,
// so when the system runs low on memory items will be deleted. To
// improve performance further, when some item has been garbage collected
// the entry is deleted from the map completely.
// The cache uses generics to allow a cache of anything, such as filenames
// to Image objects. (Here I only use String and Date.)
//
// In addition a WeakHashMap is used for the same purpose. The output
// shows what happens when the garbage collector is run.
//
// Written 3/2010 by Wayne Pollock, Tampa Florida USA
import java.lang.ref.*;
import java.util.*;
class Cache <T>
{
Map<String,SoftReference<T>> cache =
new HashMap<String,SoftReference<T>>();
public T get ( String name )
{
SoftReference<T> ref = cache.get( name );
T item = null;
if ( ref != null )
{
item = ref.get();
if ( item == null )
cache.remove( name ); // clean out cache
return item;
}
return null;
}
public void put ( String name, T item )
{
cache.put( name, new SoftReference<T>(item) );
}
}
public class GenericRefDemo
{
public static void main ( String [] args )
{
Calendar cal = Calendar.getInstance();
System.out.println("\n****** Cache Using Soft References ******\n\n");
Cache<Date> birthday = new Cache<Date>();
cal.set(1958,4,25);
Date d = cal.getTime();
birthday.put( "Wayne", d);
cal.set(1809, 2, 12);
d = cal.getTime();
birthday.put( "Abe", d);
System.out.println("Lincoln's Birthday: " + birthday.get("Abe") );
System.out.println("Washington's Birthday: " + birthday.get("George") );
System.gc();
System.out.println("\n(Ran garbage collector)\n");
System.out.println("Lincoln's Birthday: " + birthday.get("Abe") );
System.out.println("\n\n****** Using Weak References *******\n\n");
Map<String,Date> map = new WeakHashMap<String,Date>();
String name = new String("Lincoln");
cal.set(2009, 4, 1);
d = cal.getTime();
map.put(name, d); // Try this using a String literal for name!
System.out.println("Lincoln's Birthday: " + map.get("Lincoln") );
System.gc();
System.out.println("\n(Ran garbage collector)\n");
System.out.println("Lincoln's Birthday: " + map.get("Lincoln") );
name = null;
System.gc();
System.out.println("\n(Ran garbage collector after nulling out \"name\")");
System.out.println("Lincoln's Birthday: " + map.get("Lincoln") );
}
}