public final class Cache
extends java.lang.Object
implements java.io.Closeable, java.io.Flushable
To measure cache effectiveness, this class tracks three statistics:
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 7234) cache headers, it doesn't cache partial responses.
In some situations, such as after a user clicks a 'refresh' button, it may be necessary to
skip the cache, and fetch data directly from the server. To force a full refresh, add the no-cache
directive:
Request request = new Request.Builder()
.cacheControl(new CacheControl.Builder().noCache().build())
.url("http://publicobject.com/helloworld.txt")
.build();
If it is only necessary to force a cached response to be validated by the server, use the more
efficient max-age=0
directive instead:
Request request = new Request.Builder()
.cacheControl(new CacheControl.Builder()
.maxAge(0, TimeUnit.SECONDS)
.build())
.url("http://publicobject.com/helloworld.txt")
.build();
Sometimes you'll want to show resources if they are available immediately, but not otherwise.
This can be used so your application can show something while waiting for the latest data
to be downloaded. To restrict a request to locally-cached resources, add the only-if-cached
directive:
Request request = new Request.Builder()
.cacheControl(new CacheControl.Builder()
.onlyIfCached()
.build())
.url("http://publicobject.com/helloworld.txt")
.build();
Response forceCacheResponse = client.newCall(request).execute();
if (forceCacheResponse.code() != 504) {
// The resource was cached! Show it.
} else {
// 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:
Request request = new Request.Builder()
.cacheControl(new CacheControl.Builder()
.maxStale(365, TimeUnit.DAYS)
.build())
.url("http://publicobject.com/helloworld.txt")
.build();
The CacheControl
class can configure request caching directives and parse response
caching directives. It even offers convenient constants CacheControl.FORCE_NETWORK
and
CacheControl.FORCE_CACHE
that address the use cases above.
Modifier and Type | Class and Description |
---|---|
private class |
Cache.CacheRequestImpl |
private static class |
Cache.CacheResponseBody |
private static class |
Cache.Entry |
Modifier and Type | Field and Description |
---|---|
(package private) DiskLruCache |
cache |
private static int |
ENTRY_BODY |
private static int |
ENTRY_COUNT |
private static int |
ENTRY_METADATA |
private int |
hitCount |
(package private) InternalCache |
internalCache |
private int |
networkCount |
private int |
requestCount |
private static int |
VERSION |
(package private) int |
writeAbortCount |
(package private) int |
writeSuccessCount |
Constructor and Description |
---|
Cache(java.io.File directory,
long maxSize)
Create a cache of at most
maxSize bytes in directory . |
Cache(java.io.File directory,
long maxSize,
FileSystem fileSystem) |
Modifier and Type | Method and Description |
---|---|
private void |
abortQuietly(DiskLruCache.Editor editor) |
void |
close() |
void |
delete()
Closes the cache and deletes all of its stored values.
|
java.io.File |
directory() |
void |
evictAll()
Deletes all values stored in the cache.
|
void |
flush() |
(package private) Response |
get(Request request) |
int |
hitCount() |
void |
initialize()
Initialize the cache.
|
boolean |
isClosed() |
static java.lang.String |
key(HttpUrl url) |
long |
maxSize()
Max size of the cache (in bytes).
|
int |
networkCount() |
(package private) CacheRequest |
put(Response response) |
(package private) static int |
readInt(okio.BufferedSource source) |
(package private) void |
remove(Request request) |
int |
requestCount() |
long |
size() |
(package private) void |
trackConditionalCacheHit() |
(package private) void |
trackResponse(CacheStrategy cacheStrategy) |
(package private) void |
update(Response cached,
Response network) |
java.util.Iterator<java.lang.String> |
urls()
Returns an iterator over the URLs in this cache.
|
int |
writeAbortCount() |
int |
writeSuccessCount() |
private static final int VERSION
private static final int ENTRY_METADATA
private static final int ENTRY_BODY
private static final int ENTRY_COUNT
final InternalCache internalCache
final DiskLruCache cache
int writeSuccessCount
int writeAbortCount
private int networkCount
private int hitCount
private int requestCount
public Cache(java.io.File directory, long maxSize)
maxSize
bytes in directory
.Cache(java.io.File directory, long maxSize, FileSystem fileSystem)
public static java.lang.String key(HttpUrl url)
@Nullable CacheRequest put(Response response)
void remove(Request request) throws java.io.IOException
java.io.IOException
private void abortQuietly(@Nullable DiskLruCache.Editor editor)
public void initialize() throws java.io.IOException
The initialization time may vary depending on the journal file size and the current actual cache size. The application needs to be aware of calling this function during the initialization phase and preferably in a background worker thread.
Note that if the application chooses to not call this method to initialize the cache. By default, the okhttp will perform lazy initialization upon the first usage of the cache.
java.io.IOException
public void delete() throws java.io.IOException
java.io.IOException
public void evictAll() throws java.io.IOException
java.io.IOException
public java.util.Iterator<java.lang.String> urls() throws java.io.IOException
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.
java.io.IOException
public int writeAbortCount()
public int writeSuccessCount()
public long size() throws java.io.IOException
java.io.IOException
public long maxSize()
public void flush() throws java.io.IOException
flush
in interface java.io.Flushable
java.io.IOException
public void close() throws java.io.IOException
close
in interface java.io.Closeable
close
in interface java.lang.AutoCloseable
java.io.IOException
public java.io.File directory()
public boolean isClosed()
void trackResponse(CacheStrategy cacheStrategy)
void trackConditionalCacheHit()
public int networkCount()
public int hitCount()
public int requestCount()
static int readInt(okio.BufferedSource source) throws java.io.IOException
java.io.IOException