Created
October 10, 2013 16:22
-
-
Save kwon37xi/6921207 to your computer and use it in GitHub Desktop.
Google Guava cache에서 캐시의 특정 키에 값이 없는 상태에서 여러 쓰레드에서
요청이 들어와도 최초 요청 쓰레드 하나만 값을 가져오는 코드를 실행하고,
나머지는 기다렸가가 캐시의 결과를 리턴 받는 것을 시연한다.
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
package kr.pe.kwonnam.guavatest.cache; | |
import com.google.common.cache.CacheBuilder; | |
import com.google.common.cache.CacheLoader; | |
import com.google.common.cache.LoadingCache; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* Google Guava cache에서 캐시의 특정 키에 값이 없는 상태에서 여러 쓰레드에서 | |
* 요청이 들어와도 최초 요청 쓰레드 하나만 값을 가져오는 코드를 실행하고, | |
* 나머지는 기다렸가가 캐시의 결과를 리턴 받는 것을 시연한다. | |
* <p/> | |
* Author: KwonNam Son(kwon37xi@gmail.com) | |
*/ | |
public class CacheLockTest { | |
public static void main(String[] args) throws Exception { | |
LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(5).expireAfterWrite(10, TimeUnit.MINUTES).build(new CacheLoader<String, String>() { | |
@Override | |
public String load(String key) throws Exception { | |
for (int i = 1; i <= 10; i++) { | |
System.out.println("sleeping " + i + " times " + Thread.currentThread().getName()); | |
Thread.sleep(1000); | |
} | |
return "I'm fine, thank you, and you?"; | |
} | |
}); | |
for (int i = 0; i < 10; i++) { | |
new Thread(new CacheAccessor(cache)).start(); | |
Thread.sleep(200); | |
} | |
} | |
private static class CacheAccessor implements Runnable { | |
private LoadingCache<String, String> cache; | |
public CacheAccessor(LoadingCache<String, String> cache) { | |
this.cache = cache; | |
} | |
@Override | |
public void run() { | |
try { | |
String threadName = Thread.currentThread().getName(); | |
System.out.println(threadName + " request a value to the cache."); | |
String result = cache.get("How are you?"); | |
System.out.println("Thread " + threadName + " got answer \"" + result + "\"."); | |
} catch (ExecutionException e) { | |
throw new RuntimeException(e.getMessage(), e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
결과는 모든 쓰레드가 하나의 쓰레드를 기다려서 받는 것을 확인시켜 준다.