Created
May 15, 2017 08:36
-
-
Save thermosym/da178d3829b0dc8ac7ffdee972eb64ec to your computer and use it in GitHub Desktop.
Loading Cache Asynchronous Reloading Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.cache.CacheBuilder; | |
import com.google.common.cache.CacheLoader; | |
import com.google.common.cache.LoadingCache; | |
import com.google.common.util.concurrent.ListenableFuture; | |
import com.google.common.util.concurrent.ListenableFutureTask; | |
import org.junit.Test; | |
import java.time.LocalDateTime; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.TimeUnit; | |
public class CacheTest { | |
@Test | |
public void testLoadingCache() throws Exception { | |
ExecutorService es = Executors.newFixedThreadPool(1); | |
LoadingCache<String, String> cache = CacheBuilder.newBuilder() | |
.refreshAfterWrite(1, TimeUnit.SECONDS) | |
.build(new CacheLoader<String, String>() { | |
@Override | |
public String load(String s) throws Exception { | |
System.out.println(" start synchronous loading "); | |
return s + LocalDateTime.now().toString(); | |
} | |
@Override | |
public ListenableFuture<String> reload(String s, String oldValue) { | |
System.out.println(" start asynchronous reloading "); | |
ListenableFutureTask<String> task = ListenableFutureTask.create(() -> { | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
} | |
return s + LocalDateTime.now().toString(); | |
}); | |
task.addListener(() -> System.out.println("finish asynchronous reloading "), es); | |
es.submit(task); | |
return task; | |
} | |
}); | |
for (int i=0; i< 10; i++) { | |
String result = cache.get("1"); | |
System.out.println("result = " + result); | |
Thread.sleep(500); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment