Last active
June 18, 2020 21:48
-
-
Save abachar/7f061669d2954f56a15881987d7d9621 to your computer and use it in GitHub Desktop.
caffeine getAll
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 consulting.crafter.cache; | |
import com.github.benmanes.caffeine.cache.CacheLoader; | |
import com.github.benmanes.caffeine.cache.Caffeine; | |
import com.github.benmanes.caffeine.cache.LoadingCache; | |
import org.checkerframework.checker.nullness.qual.NonNull; | |
import org.checkerframework.checker.nullness.qual.Nullable; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.concurrent.TimeUnit; | |
import static java.util.Arrays.asList; | |
import static java.util.Collections.emptyList; | |
import static java.util.Collections.singletonList; | |
public class Main { | |
public static void main(String[] args) { | |
LoadingCache<String, String> cache = Caffeine.newBuilder() | |
.maximumSize(100) | |
.expireAfterWrite(5, TimeUnit.MINUTES) | |
.refreshAfterWrite(1, TimeUnit.MINUTES) | |
.build(new CacheLoader<String, String>() { | |
@Nullable | |
@Override | |
public String load(@NonNull String key) throws Exception { | |
System.out.println("+> Loading keys " + String.join(",", key)); | |
return "Loaded-" + key; | |
} | |
@Override | |
public @NonNull Map<String, String> loadAll(@NonNull Iterable<? extends String> keys) throws Exception { | |
System.out.println("-> Loading keys " + String.join(",", keys)); | |
Map<String, String> retval = new HashMap<>(); | |
keys.forEach(key -> { | |
retval.put(key, "Loaded-" + key); | |
}); | |
return retval; | |
} | |
}); | |
System.out.println("<-" + String.join(",", cache.getAll(singletonList("1")).values())); | |
System.out.println("<-" + String.join(",", cache.getAll(asList("1", "2")).values())); | |
System.out.println("<-" + String.join(",", cache.getAll(asList("1", "2", "3")).values())); | |
System.out.println("<-" + String.join(",", cache.getAll(asList("1", "2", "3", "4")).values())); | |
System.out.println("<-" + String.join(",", cache.getAll(asList("4", "1")).values())); | |
System.out.println("<-" + cache.get("4")); | |
// Only this will use load because we're loading one element and it doesn't exist in cache | |
System.out.println("<-" + cache.get("5")); | |
System.out.println("<-" + cache.getAll(emptyList())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment