HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Caching and Weak References"
Volume: 3 Issue: 8 p. 32

	

Listing 1.
 
import java.lang.ref.*; 
import java.util.*; 

public class SimpleCache extends Hashtable 
{ 
} 

Listing 2.
 
import java.lang.ref.*; 
import java.util.*; 
  

public class Cache extends AbstractMap 
{ 
 private Map map = new Hashtable(); 
 public synchronized Set entries() 
 { 
  Map   newMap; 
  Iterator iter; 

  newMap = new Hashtable(); 
  iter = map.entries().iterator(); 
  while( iter.hasNext() ) 
  { 
   Map.Entry me = (Map.Entry)iter.next(); 
   Reference ref = 
    (Reference)me.getValue(); 
   Object o = ref.get(); 
   if ( o==null ) 
   { 
    // Delete cleared reference 
    iter.remove(); 
   } 
   else 
   { 
    // Copy out interior object 
    newMap.put( me.getKey(), o ); 
   } 
  } 

  // Return set of interior objects 
  return newMap.entries(); 
 } 
  

 public synchronized 
  Object put( Object key, Object value ) 
 { 
  Reference ref = 
   new WeakReference( value ); 
  ref = (Reference)map.put( key, ref ); 
  if (ref!=null) 
   return(ref.get()); 
  return null; 
 } 
} 
  

Listing 3.
 
Garbage collecting 
Added class java.lang.String 
 Cache still holds key 0 
Added class java.lang.String 
Garbage collecting 
Releasing direct reference 
 Cache still holds key 1 
 Cache still holds key 0 
Releasing direct reference 
Added class java.lang.String 
Garbage collecting 
 Cache still holds key 2 
Releasing direct reference 
  
      
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.