public final class Cache extends Object
GET
. The server will then send either the updated response if it has
changed, or a short 'not modified' response if the client's copy is still
valid. Such responses increment both the network count and hit count.
The best way to improve the cache hit rate is by configuring the web server to return cacheable responses. Although this client honors all HTTP/1.1 (RFC 2068) cache headers, it doesn't cache partial responses.
no-cache
directive:
connection.addRequestProperty("Cache-Control", "no-cache");
If it is only necessary to force a cached response to be validated by the
server, use the more efficient max-age=0
instead:
connection.addRequestProperty("Cache-Control", "max-age=0");
only-if-cached
directive:
try {
connection.addRequestProperty("Cache-Control", "only-if-cached");
InputStream cached = connection.getInputStream();
// the resource was cached! show it
} catch (FileNotFoundException e) {
// the resource was not cached
}
This technique works even better in situations where a stale response is
better than no response. To permit stale cached responses, use the max-stale
directive with the maximum staleness in seconds:
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
Modifier and Type | Method and Description |
---|---|
void |
close() |
void |
delete()
Closes the cache and deletes all of its stored values.
|
void |
evictAll()
Deletes all values stored in the cache.
|
void |
flush() |
File |
getDirectory() |
int |
getHitCount() |
long |
getMaxSize() |
int |
getNetworkCount() |
int |
getRequestCount() |
long |
getSize() |
int |
getWriteAbortCount() |
int |
getWriteSuccessCount() |
boolean |
isClosed() |
Iterator<String> |
urls()
Returns an iterator over the URLs in this cache.
|
public Cache(File directory, long maxSize) throws IOException
IOException
public void delete() throws IOException
IOException
public void evictAll() throws IOException
IOException
public Iterator<String> urls()
ConcurrentModificationException
, but if new responses are added while iterating, their URLs
will not be returned. If existing responses are evicted during iteration, they will be absent
(unless they were already returned).
The iterator supports Iterator.remove(). Removing a URL from the iterator evicts the corresponding response from the cache. Use this to evict selected responses.
public int getWriteAbortCount()
public int getWriteSuccessCount()
public long getSize()
public long getMaxSize()
public void flush() throws IOException
IOException
public void close() throws IOException
IOException
public File getDirectory()
public boolean isClosed()
public int getNetworkCount()
public int getHitCount()
public int getRequestCount()
Copyright © 2015. All rights reserved.