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
 

"How To Use Java SoftReferences for Caching"
Vol. 5, Issue 7, p. 54

	

Listing 1: 

import java.awt.*; 
import java.lang.ref.*; 
public class ImageButton extends Button { 
private SoftReference imageReference=null; 
public ImageButton() { 
super(); 
} 
public void paint(Graphics g) { 
Image image=null; 
if (imageReference != null) // null first time we paint 
image = (Image)imageReference.get(); 
if (image == null) { 
image = loadImage("Image name"); 
imageReference = new SoftReference(image); 
} 
. 
. 
. 
image = null; 
} 
public Image loadImage(String name) { 
. 
. 
. 
} 
} 
} 
 
Listing 2: 

} 
import java.lang.ref.*; 
import java.util.Vector; 
public class SoftCache { 
Vector vector=null; 
Thread remover; 
ReferenceQueue clearedRefs; 
public SoftCache() { 
vector = new Vector(); 
clearedRefs = new ReferenceQueue(); 
// start thread to delete cleared references from the cache 
remover = new Remover(clearedRefs,vector); 
remover.start(); 
} 
public void put(Object o) { 
synchronized (vector) { 
vector.addElement(new SoftReference(o,clearedRefs)); 
} 
} 
public Object get() { 
synchronized (vector) { 
if (vector.size() > 0) { 
SoftReference sr = (SoftReference)vector.elementAt(0); 
vector.remove(0); 
return sr.get(); 
} 
} 
return null; 
} 
private class Remover extends Thread { 
ReferenceQueue refQ; 
Vector cache; 
public Remover (ReferenceQueue rq, Vector v) { 
super(); 
refQ = rq; 
cache = v; 
setDaemon(true); 
} 
public void run() { 
try { 
while (true) { 
Object o = refQ.remove(); 
synchronized (cache) { 
cache.removeElement(o); 
System.out.println("Removing " + o); 
} 
} 
} catch (InterruptedException e) { ; } 
} 
} 
} 
  
 
 

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.