📄 perf4.html
字号:
<H3>Caching Many Objects</H3>
Sometimes you will want to cache more than one object. For example,
you might want to keep the most recently accessed files on a web server
in a cache. If you use a <CODE>HashMap</CODE> object for a purpose
like this, it will continue to grow and use a lot of memory.
<P>
If your machine has large amounts of memory and only a small number of objects
to cache then a growing <CODE>HashMap</CODE> may not be a problem.
However, if you are intending to cache alot of objects then you may find
that keeping only the most recent
objects in the cache provides the best use of the machines memory. You can combine a <CODE>HashMap</CODE> object with a
<CODE>LinkedList</CODE> to create what is called a Most Recently Used
(MRU) cache.
<P>
<HR>
<BLOCKQUOTE>
<STRONG>Note:</STRONG> There are other techniques used to constrain cache size besides MRU. MRU is one of the simpler algorithms.
</BLOCKQUOTE>
<HR>
<P>
With an MRU cache, you can place a constraint on which objects remain
in cache, and thereby, control the size of the cache. There are three main
operations that the MRU cache has to perform:
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">If the cache is not full, new objects not already in the cache
are inserted at the head of the list. </FONT>
<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">If the cache is not full and the object to be inserted already exists in
the cache, it is moved to the head of the list.</FONT>
<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">If the cache is full and a new object is to be inserted, the last object
in the cache is removed and the new object is inserted at the head of
the list.</FONT>
</UL>
This diagram shows how the <CODE>LinkedList</CODE> and
<CODE>HashMap</CODE> work together to implement the operations
described above. A discussion of the diagram follows.
<P>
<IMG SRC="./Art/cache.gif">
<P>
<DIV ALIGN="CENTER"><STRONG>MRU Cache with LinkedList and HashMap</STRONG></DIV>
<P>
The <CODE>LinkedList</CODE> provides the queue mechanism, and the entries
in the <CODE>LinkedList</CODE> contain the key to the data in the <CODE>
HashMap</CODE>. To add a new entry to the front of the list, the
<CODE>addFirst</CODE> method is called.
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">If the list is already full, the <CODE>removeLast</CODE> method
is called and the data entry is also removed
from the <CODE>HashMap</CODE>.</FONT>
<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
If an entry was already in the list, it is removed with
a call to the <CODE>remove</CODE> method and inserted at the front of the list with
a call to the <CODE>addFirst</CODE> method. </FONT>
</UL>
The Collections API does not implement locking, so if you remove entries
from or add entries to <CODE>LinkedList</CODE> or <CODE>HashMap</CODE>
objects, you need to
lock access to these objects. You can also use a <CODE>Vector</CODE> or
<CODE>ArrayList</CODE> to get the same results as shown in the code
below with the <CODE>LinkedList</CODE>.
<P>
This <A HREF="./Code/MRUCache.java">code example</A>
uses an MRU cache to keep a cache of files loaded from disk.
When a file is requested, the program checks to see if the file
is in the cache.
If the file is not in the cache, the program reads
the file from disk and places the cache copy at the
beginning of the list.
<P>
If the file is in cache, the program compares the
modification times of the file and cache entry.
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">If the cache entry time is older, the
program reads the file from disk, removes the cache copy, and places
a new copy in the cache at the front of the <CODE>LinkedList</CODE>.</FONT>
<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">If the file time is older, the program gets the file from
the cache and moves the cache copy to the front of the list. </FONT>
</UL>
</FONT>
<PRE>
import java.util.*;
import java.io.*;
class myFile {
long lastmodified;
String contents;
public myFile(long last, String data) {
lastmodified=last;
contents=data;
}
public long getLastModified() {
return lastmodified;
}
public String getContents() {
return contents;
}
}
public class MRUCache {
Map cache;
LinkedList mrulist;
int cachesize;
public MRUCache(int max) {
cache = new HashMap();
mrulist= new LinkedList();
cachesize=max;
}
public String getFile(String fname) {
if(!cache.containsKey(fname)) {
synchronized(cache) {
if(mrulist.size() >=cachesize) {
cache.remove(mrulist.getLast());
mrulist.removeLast();
}
cache.put(fname, readFile(fname));
mrulist.addFirst(fname);
}
} else {
if((new File(fname).lastModified())>
((myFile)cache.get(fname)).getLastModified()) {
synchronized(cache) {
cache.put(fname, readFile(fname));
}
}
synchronized(cache) {
mrulist.remove(fname);
mrulist.addFirst(fname);
}
}
return ((myFile)cache.get(fname)).getContents();
}
public myFile readFile(String name) {
File f = new File(name);
StringBuffer filecontents= new StringBuffer();
try {
BufferedReader br=new BufferedReader(
new FileReader(f));
String line;
while((line =br.readLine()) != null) {
filecontents.append(line);
}
} catch (FileNotFoundException fnfe){
return (null);
} catch ( IOException ioe) {
return (null);
}
return (new myFile(f.lastModified(),
filecontents.toString()));
}
public void printList() {
for(int i=0;i<mrulist.size();i++) {
System.out.println("item "+i+"="+mrulist.get(i));
}
}
public static void main(String args[]) {
// Number of entries in MRU cache is set to 10
MRUCache h1=new MRUCache(10);
for(int i=1;i<=20;i++) {
// files are stored in a subdirectory called data
h1.getFile("data"+File.separatorChar+i);
}
h1.printList();
}
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P ALIGN="RIGHT">
<FONT SIZE="-1">[<A HREF="#top">TOP</A>]</FONT>
</FONT>
</TD>
</TR>
</TABLE>
<!-- ================ -->
<!-- End Main Content -->
<!-- ================ -->
</TD>
</TR>
</TABLE>
<!-- Copyright Insert -->
<BR CLEAR="ALL">
<FORM ACTION="/cgi-bin/search.cgi" METHOD="POST">
<TABLE WIDTH="100%" CELLPADDING="0" BORDER="0" CELLSPACING="5">
<TR>
<TD VALIGN="TOP">
<P ALIGN=CENTER>
<FONT SIZE="-1" COLOR="#999999" FACE="Verdana, Arial, Helvetica, sans-serif">
[ This page was updated: <!-- new date --> 13-Oct-99 ]</font></P>
</TD>
</TR>
<TR>
<TD BGCOLOR="#CCCCCC">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<CENTER>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="http://java.sun.com/products/">Products & APIs</A> |
<A HREF="/developer/index.html">Developer Connection</A> |
<A HREF="/developer/infodocs/index.shtml">Docs & Training</A> |
<A HREF="/developer/support/index.html">Online Support</A><BR>
<A HREF="/developer/community/index.html">Community Discussion</A> |
<A HREF="http://java.sun.com/industry/">Industry News</A> |
<A HREF="http://java.sun.com/solutions">Solutions Marketplace</A> |
<A HREF="http://java.sun.com/casestudies">Case Studies</A>
</FONT>
</CENTER>
</TD>
</TR>
<TR>
<TD BGCOLOR="#CCCCCC">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD ALIGN="CENTER">
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="http://java.sun.com/docs/glossary.html">Glossary</A> -
<A HREF="http://java.sun.com/applets/">Applets</A> -
<A HREF="http://java.sun.com/docs/books/tutorial/">Tutorial</A> -
<A HREF="http://java.sun.com/jobs/">Employment</A> -
<A HREF="http://java.sun.com/nav/business/">Business & Licensing</A> -
<A HREF="http://java.sun.com/javastore/">Java Store</A> -
<A HREF="http://java.sun.com/casestudies/">Java in the Real World</A>
</FONT>
</TD>
</TR>
<TR>
<TD>
<CENTER>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<a href="/siteinfo/faq.html">FAQ</a> |
<a href="/feedback/index.html">Feedback</a> |
<a href="http://www.dynamicdiagrams.net/mapa/cgi-bin/help.tcl?db=javasoft&dest=http://java.sun.com/">Map</a> |
<A HREF="http://java.sun.com/a-z/index.html">A-Z Index</A>
</FONT>
</CENTER>
</TD>
</TR>
<TR>
<TD>
<TABLE WIDTH="100%" CELLPADDING="0" BORDER="0" CELLSPACING="0">
<TR>
<TD WIDTH="50%">
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
For more information on Java technology<BR>
and other software from Sun Microsystems, call:<BR>
</FONT>
<FONT SIZE="-1" FACE="Verdana, Arial, Helvetica, sans-serif">
(800) 786-7638<BR></FONT>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
Outside the U.S. and Canada, dial your country's
<A HREF="http://www.att.com/business_traveler/attdirecttollfree/">AT&T Direct Access Number</A> first.<BR>
</FONT>
</TD>
<TD ALIGN="RIGHT" WIDTH="50%">
<A HREF="http://www.sun.com"><IMG SRC="/images/lgsun.gif" width="64" height="30" border="0" ALT="Sun Microsystems, Inc."></A><BR>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
Copyright © 1995-99
<A HREF="http://www.sun.com">Sun Microsystems, Inc.</A><BR>
All Rights Reserved.
<a href="http://www.sun.com/share/text/SMICopyright.html">Legal Terms</a>.
<A HREF="http://www.sun.com/privacy/">Privacy Policy</A>.
</FONT>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</FORM>
<!-- End Copyright Insert -->
</BODY>
</HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -