use of com.google.common.base.Ticker in project caffeine by ben-manes.
the class GuavaCacheFromContext method newGuavaCache.
/** Returns a Guava-backed cache. */
@SuppressWarnings("CheckReturnValue")
public static <K, V> Cache<K, V> newGuavaCache(CacheContext context) {
checkState(!context.isAsync(), "Guava caches are synchronous only");
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
context.guava = builder;
builder.concurrencyLevel(1);
if (context.initialCapacity != InitialCapacity.DEFAULT) {
builder.initialCapacity(context.initialCapacity.size());
}
if (context.isRecordingStats()) {
builder.recordStats();
}
if (context.maximumSize != Maximum.DISABLED) {
if (context.weigher == CacheWeigher.DEFAULT) {
builder.maximumSize(context.maximumSize.max());
} else {
builder.weigher(new GuavaWeigher<Object, Object>(context.weigher));
builder.maximumWeight(context.maximumWeight());
}
}
if (context.afterAccess != Expire.DISABLED) {
builder.expireAfterAccess(context.afterAccess.timeNanos(), TimeUnit.NANOSECONDS);
}
if (context.afterWrite != Expire.DISABLED) {
builder.expireAfterWrite(context.afterWrite.timeNanos(), TimeUnit.NANOSECONDS);
}
if (context.refresh != Expire.DISABLED) {
builder.refreshAfterWrite(context.refresh.timeNanos(), TimeUnit.NANOSECONDS);
}
if (context.expires() || context.refreshes()) {
builder.ticker(context.ticker());
}
if (context.keyStrength == ReferenceType.WEAK) {
builder.weakKeys();
} else if (context.keyStrength == ReferenceType.SOFT) {
throw new IllegalStateException();
}
if (context.valueStrength == ReferenceType.WEAK) {
builder.weakValues();
} else if (context.valueStrength == ReferenceType.SOFT) {
builder.softValues();
}
if (context.removalListenerType != Listener.DEFAULT) {
boolean translateZeroExpire = (context.afterAccess == Expire.IMMEDIATELY) || (context.afterWrite == Expire.IMMEDIATELY);
builder.removalListener(new GuavaRemovalListener<>(translateZeroExpire, context.removalListener));
}
Ticker ticker = (context.ticker == null) ? Ticker.systemTicker() : context.ticker();
if (context.loader == null) {
context.cache = new GuavaCache<>(builder.<Integer, Integer>build(), ticker, context.isRecordingStats());
} else if (context.loader().isBulk()) {
context.cache = new GuavaLoadingCache<>(builder.build(new BulkLoader<Integer, Integer>(context.loader())), ticker, context.isRecordingStats());
} else {
context.cache = new GuavaLoadingCache<>(builder.build(new SingleLoader<Integer, Integer>(context.loader())), ticker, context.isRecordingStats());
}
@SuppressWarnings("unchecked") Cache<K, V> castedCache = (Cache<K, V>) context.cache;
return castedCache;
}
use of com.google.common.base.Ticker in project cassandra by apache.
the class RateLimitingTest method resetLimits.
@Before
public void resetLimits() {
// Reset to the original start time in case a test advances the clock.
tick = new AtomicLong(ClientResourceLimits.GLOBAL_REQUEST_LIMITER.getStartedNanos());
ticker = new Ticker() {
@Override
public long read() {
return tick.get();
}
};
ClientResourceLimits.setGlobalLimit(Long.MAX_VALUE);
}
use of com.google.common.base.Ticker in project gerrit by GerritCodeReview.
the class GerritServer method start.
/**
* Starts Gerrit server from existing on-disk site.
*
* @param desc server description.
* @param baseConfig default config values; merged with config from {@code desc}.
* @param site existing temporary directory for site. Required, but may be empty, for in-memory
* servers. For on-disk servers, assumes that {@link #init} was previously called to
* initialize this directory. Can be retrieved from the returned instance via {@link
* #getSitePath()}.
* @param testSysModule optional additional module to add to the system injector.
* @param testSshModule optional additional module to add to the ssh injector.
* @param inMemoryRepoManager {@link InMemoryRepositoryManager} that should be used if the site is
* started in memory
* @param additionalArgs additional command-line arguments for the daemon program; only allowed if
* the test is not in-memory.
* @return started server.
*/
public static GerritServer start(Description desc, Config baseConfig, Path site, @Nullable Module testSysModule, @Nullable Module testAuditModule, @Nullable Module testSshModule, @Nullable InMemoryRepositoryManager inMemoryRepoManager, String... additionalArgs) throws Exception {
checkArgument(site != null, "site is required (even for in-memory server");
desc.checkValidAnnotations();
TestLoggingActivator.configureLogging();
CyclicBarrier serverStarted = new CyclicBarrier(2);
Daemon daemon = new Daemon(() -> {
try {
serverStarted.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
}, site);
daemon.setEmailModuleForTesting(new FakeEmailSenderModule());
daemon.setAuditEventModuleForTesting(MoreObjects.firstNonNull(testAuditModule, new FakeGroupAuditServiceModule()));
if (testSysModule != null) {
daemon.addAdditionalSysModuleForTesting(testSysModule);
}
if (testSshModule != null) {
daemon.addAdditionalSshModuleForTesting(testSshModule);
}
daemon.setEnableSshd(desc.useSsh());
daemon.addAdditionalSysModuleForTesting(new AbstractModule() {
@Override
protected void configure() {
bind(CommitValidationListener.class).annotatedWith(Exports.named("object-visibility-listener")).to(GitObjectVisibilityChecker.class);
}
});
daemon.addAdditionalSysModuleForTesting(new AbstractModule() {
@Override
protected void configure() {
super.configure();
// GerritServer isn't restarted between tests. TestTicker allows to replace actual
// Ticker in tests without restarting server and transparently for other code.
// Alternative option with Provider<Ticker> is less convinient, because it affects how
// gerrit code should be written - i.e. Ticker must not be stored in fields and must
// always be obtained from the provider.
TestTicker testTicker = new TestTicker();
OptionalBinder.newOptionalBinder(binder(), Ticker.class).setBinding().toInstance(testTicker);
bind(TestTicker.class).toInstance(testTicker);
}
});
if (desc.memory()) {
checkArgument(additionalArgs.length == 0, "cannot pass args to in-memory server");
return startInMemory(desc, site, baseConfig, daemon, inMemoryRepoManager);
}
return startOnDisk(desc, site, daemon, serverStarted, additionalArgs);
}
use of com.google.common.base.Ticker in project guava by google.
the class CacheBuilderTest method testTicker_setTwice.
public void testTicker_setTwice() {
Ticker testTicker = Ticker.systemTicker();
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().ticker(testTicker);
try {
// even to the same instance is not allowed
builder.ticker(testTicker);
fail();
} catch (IllegalStateException expected) {
}
}
use of com.google.common.base.Ticker in project guava by google.
the class LocalCacheTest method testSerializationProxyLoading.
public void testSerializationProxyLoading() {
CacheLoader<Object, Object> loader = new SerializableCacheLoader();
RemovalListener<Object, Object> listener = new SerializableRemovalListener<>();
SerializableWeigher<Object, Object> weigher = new SerializableWeigher<>();
Ticker ticker = new SerializableTicker();
// createMock
@SuppressWarnings("unchecked") LocalLoadingCache<Object, Object> one = (LocalLoadingCache) CacheBuilder.newBuilder().weakKeys().softValues().expireAfterAccess(123, SECONDS).expireAfterWrite(456, MINUTES).maximumWeight(789).weigher(weigher).concurrencyLevel(12).removalListener(listener).ticker(ticker).build(loader);
// add a non-serializable entry
one.getUnchecked(new Object());
assertEquals(1, one.size());
assertFalse(one.asMap().isEmpty());
LocalLoadingCache<Object, Object> two = SerializableTester.reserialize(one);
assertEquals(0, two.size());
assertTrue(two.asMap().isEmpty());
LocalCache<Object, Object> localCacheOne = one.localCache;
LocalCache<Object, Object> localCacheTwo = two.localCache;
assertEquals(localCacheOne.keyStrength, localCacheTwo.keyStrength);
assertEquals(localCacheOne.keyStrength, localCacheTwo.keyStrength);
assertEquals(localCacheOne.valueEquivalence, localCacheTwo.valueEquivalence);
assertEquals(localCacheOne.valueEquivalence, localCacheTwo.valueEquivalence);
assertEquals(localCacheOne.maxWeight, localCacheTwo.maxWeight);
assertEquals(localCacheOne.weigher, localCacheTwo.weigher);
assertEquals(localCacheOne.expireAfterAccessNanos, localCacheTwo.expireAfterAccessNanos);
assertEquals(localCacheOne.expireAfterWriteNanos, localCacheTwo.expireAfterWriteNanos);
assertEquals(localCacheOne.refreshNanos, localCacheTwo.refreshNanos);
assertEquals(localCacheOne.removalListener, localCacheTwo.removalListener);
assertEquals(localCacheOne.ticker, localCacheTwo.ticker);
// serialize the reconstituted version to be sure we haven't lost the ability to reserialize
LocalLoadingCache<Object, Object> three = SerializableTester.reserialize(two);
LocalCache<Object, Object> localCacheThree = three.localCache;
assertEquals(localCacheTwo.defaultLoader, localCacheThree.defaultLoader);
assertEquals(localCacheTwo.keyStrength, localCacheThree.keyStrength);
assertEquals(localCacheTwo.keyStrength, localCacheThree.keyStrength);
assertEquals(localCacheTwo.valueEquivalence, localCacheThree.valueEquivalence);
assertEquals(localCacheTwo.valueEquivalence, localCacheThree.valueEquivalence);
assertEquals(localCacheTwo.maxWeight, localCacheThree.maxWeight);
assertEquals(localCacheTwo.weigher, localCacheThree.weigher);
assertEquals(localCacheTwo.expireAfterAccessNanos, localCacheThree.expireAfterAccessNanos);
assertEquals(localCacheTwo.expireAfterWriteNanos, localCacheThree.expireAfterWriteNanos);
assertEquals(localCacheTwo.removalListener, localCacheThree.removalListener);
assertEquals(localCacheTwo.ticker, localCacheThree.ticker);
}
Aggregations