2

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.

tourniquet_grab
  • 792
  • 9
  • 14

2 Answers2

8

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 2
    Thanks! Actually I had written this test and it did return the same thread ids. But the documentation confused me a bit. I thought that I was not using the cache properly. So, just to be clear, we need to overload `CacheLoader.reload` for the call to be asynchronous, right? – tourniquet_grab Oct 25 '15 at 20:05
  • 1
    Its quite late to answer , but yes you have to overload it for your CacheLoader. – Prakhar Asthana Sep 19 '17 at 13:26
2

To add to JB Nizet's answer, you can find out why Guava avoids making the cache multi-threaded by default here:

The reason for this is as follows: if we wanted to perform Cache maintenance continuously, we would need to create a thread, and its operations would be competing with user operations for shared locks. Additionally, some environments restrict the creation of threads, which would make CacheBuilder unusable in that environment.

Aidan Do
  • 86
  • 1
  • 7