Does Google Guava Cache load the cache on the same thread by default?
Code:
cache = CacheBuilder
.newBuilder()
.refreshAfterWrite(2, TimeUnit.SECONDS)
.build(new CacheLoader<String,String>() {
@Override
public String load(String s) throws Exception {
return addCache(s);
}
});
Will the call to addCache
be made on a different thread? As far as I know, it is a synchronous call but I am not sure.
Here's a simple test allowing to know:
System.out.println("Thread.currentThread() = " + Thread.currentThread());
LoadingCache<String, String> cache = CacheBuilder
.newBuilder()
.refreshAfterWrite(2, TimeUnit.SECONDS)
.build(new CacheLoader<String, String>() {
@Override
public String load(String s) throws Exception {
System.out.println("Thread.currentThread() = " + Thread.currentThread());
return "world";
}
});
cache.get("hello");
Output:
Thread.currentThread() = Thread[main,5,main]
Thread.currentThread() = Thread[main,5,main]
Of course, as the documentation indicates, if another thread has already started loading the value for the key, the current thread won't reload it: it will wait for the value to be loaded by the other one:
If another call to get(K) or getUnchecked(K) is currently loading the value for key, simply waits for that thread to finish and returns its loaded value.