Java Reference
In-Depth Information
return request ;
}
@Override
public CacheResponse get ( URI uri , String requestMethod ,
Map < String , List < String >> requestHeaders )
throws IOException {
if ( "GET" . equals ( requestMethod )) {
SimpleCacheResponse response = responses . get ( uri );
// check expiration date
if ( response != null && response . isExpired ()) {
responses . remove ( response );
response = null ;
}
return response ;
} else {
return null ;
}
}
}
Java only allows one URL cache at a time. To install or change the cache, use the static
ResponseCache.setDefault() and ResponseCache.getDefault() methods:
public static ResponseCache getDefault ()
public static void setDefault ( ResponseCache responseCache )
These set the single cache used by all programs running within the same Java virtual
machine. For example, this one line of code installs Example 7-11 in an application:
ResponseCache . setDefault ( new MemoryCache ());
Once a ResponseCache like Example 7-11 is installed, HTTP URLConnection s always
use it.
Each retrieved resource stays in the HashMap until it expires. This example waits for an
expired document to be requested again before it deletes it from the cache. A more
sophisticated implementation could use a low-priority thread to scan for expired docu‐
ments and remove them to make way for others. Instead of or in addition to this, an
implementation might cache the representations in a queue and remove the oldest
documents or those closest to their expiration date as necessary to make room for new
ones. An even more sophisticated implementation could track how often each docu‐
ment in the store was accessed and expunge only the oldest and least-used documents.
I've already mentioned that you could implement a cache on top of the filesystem instead
of on top of the Java Collections API. You could also store the cache in a database, and
you could do a lot of less-common things as well. For instance, you could redirect
requests for certain URLs to a local server rather than a remote server halfway around
the world, in essence using a local web server as the cache. Or a ResponseCache could
Search WWH ::




Custom Search