Skip to content

Instantly share code, notes, and snippets.

@tehbilly
Created June 13, 2018 18:32
Show Gist options
  • Select an option

  • Save tehbilly/044ff9064d26436d975a7574ce5a75a2 to your computer and use it in GitHub Desktop.

Select an option

Save tehbilly/044ff9064d26436d975a7574ce5a75a2 to your computer and use it in GitHub Desktop.
For gpdriver17 on reddit
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class ServiceB {
private static LoadingCache<String, Integer> thumbsUpCache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(key -> loadFromCoolGuys(key));
// Could also use full CacheLoader<K, V>, or method reference, whatever
/**
* Pretend this is the method invoked from externally
*/
public String process(String userId) {
String dbData = loadFromDatabase(userId);
Integer thumbsUp = thumbsUpCache.get(userId);
// To simulate things without using the cache, use the following instead
// Integer thumbsUp = loadFromCoolGuys(userId);
return "ThumbsUp: " + thumbsUp + ", DBData: " + dbData;
}
/**
* Simulate getting data from the database
*/
private String loadFromDatabase(String userId) {
String response = "DatabaseDataFor(" + userId + ")";
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
response = "InterruptedDatabaseCallFor(" + userId + ")";
e.printStackTrace();
}
return response;
}
/**
* Simulate fetching data from an unstable external service
*/
private static int loadFromCoolGuys(String userId) {
// 6 * 2 + 1 = 13 (quick maffs)
int randomDelay = new Random().nextInt(13);
try {
// Representing a random response time between 1 and 7 seconds
Thread.sleep((2 + randomDelay) * 500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return randomDelay;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment