Skip to content

Instantly share code, notes, and snippets.

@wreulicke
Created September 20, 2018 17:56
Show Gist options
  • Save wreulicke/8789e4a041e8a22c3ca40da6ed6102be to your computer and use it in GitHub Desktop.
Save wreulicke/8789e4a041e8a22c3ca40da6ed6102be to your computer and use it in GitHub Desktop.
やる気ない感じのランダムゆらぎの実装 with Java and Caffeine
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import javax.annotation.Nonnull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Expiry;
@Slf4j
public class CaffeineTest {
@Test
public void test() throws InterruptedException {
Cache<Object, Object> cache = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfter(new MyExpiry<>(new MyDurationGenerator<>()))
.removalListener((key, value, cause) -> log.info("expired {}: {}", key, cause))
.build();
Function<Object, Object> read = o -> {
log.info("reading...");
return o;
};
log.info("read1");
cache.get("test", read);
Thread.sleep(2000);
log.info("read2");
cache.get("test", read);
log.info("read3");
cache.get("test", read);
log.info("read4");
cache.get("test", read);
}
@RequiredArgsConstructor
static class MyExpiry<K, V> implements Expiry<K, V> {
private final DurationGenerator<K, V> generator;
@Override
public long expireAfterCreate(@Nonnull K key, @Nonnull V value, long currentTime) {
return generator.generate(key, value, currentTime);
}
@Override
public long expireAfterUpdate(@Nonnull K key, @Nonnull V value, long currentTime,
long currentDuration) {
return currentDuration;
}
@Override
public long expireAfterRead(@Nonnull K key, @Nonnull V value, long currentTime,
long currentDuration) {
return currentDuration;
}
}
interface DurationGenerator<K, V> {
long generate(@Nonnull K key, @Nonnull V value, long currentTime);
}
class MyDurationGenerator<K, V> implements DurationGenerator<K, V>{
private final Random rand = new SecureRandom();
private final long base = TimeUnit.NANOSECONDS.convert(10, TimeUnit.MINUTES) / 2;
@Override
public long generate(@Nonnull K key, @Nonnull V value, long currentTime) {
return (long) (base + 2 * base * rand.nextDouble()); // [base, 3 * base]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment