private Supplier<Map<String, Integer>> createSummaryCache() { return Suppliers.memoizeWithExpiration(new Supplier<Map<String, Integer>>() { @Override public Map<String, Integer> get() { return computeSummaryStats(); } }, 10, TimeUnit.MINUTES); }
@Override public Supplier<Boolean> apply(Supplier<Boolean> supplier) { return Suppliers.memoizeWithExpiration(supplier, Long.MAX_VALUE, TimeUnit.NANOSECONDS); } };
public ComputationResult getComputationResultForDashboardWidget(final DashboardWidget dashboardWidget) throws InvalidWidgetConfigurationException { final String widgetId = dashboardWidget.getId(); if (!this.cache.containsKey(widgetId)) { final WidgetStrategy widgetStrategy = this.widgetStrategyFactory.getWidgetForType(dashboardWidget.getType(), dashboardWidget.getConfig(), dashboardWidget.getTimeRange(), widgetId); final Supplier<ComputationResult> supplier = this.cache.putIfAbsent(widgetId, Suppliers.memoizeWithExpiration( new ComputationResultSupplier(metricRegistry, dashboardWidget, widgetStrategy), dashboardWidget.getCacheTime(), TimeUnit.SECONDS )); if (supplier == null) { // Only increment the counter if there has been no value for the widget ID before. counter.inc(); } } return this.cache.get(widgetId).get(); }
@GwtIncompatible // Thread.sleep, SerializationTester public void testMemoizeWithExpirationSerialized() throws InterruptedException { SerializableCountingSupplier countingSupplier = new SerializableCountingSupplier(); Supplier<Integer> memoizedSupplier = Suppliers.memoizeWithExpiration(countingSupplier, 75, TimeUnit.MILLISECONDS); // Calls to the original memoized supplier shouldn't affect its copy. memoizedSupplier.get(); Supplier<Integer> copy = reserialize(memoizedSupplier); memoizedSupplier.get(); CountingSupplier countingCopy = (CountingSupplier) ((Suppliers.ExpiringMemoizingSupplier<Integer>) copy).delegate; checkExpiration(countingCopy, copy); }
@GwtIncompatible // SerializationTester public void testSerialization() { assertEquals(Integer.valueOf(5), reserialize(Suppliers.ofInstance(5)).get()); assertEquals( Integer.valueOf(5), reserialize(Suppliers.compose(Functions.identity(), Suppliers.ofInstance(5))).get()); assertEquals(Integer.valueOf(5), reserialize(Suppliers.memoize(Suppliers.ofInstance(5))).get()); assertEquals( Integer.valueOf(5), reserialize(Suppliers.memoizeWithExpiration(Suppliers.ofInstance(5), 30, TimeUnit.SECONDS)) .get()); assertEquals( Integer.valueOf(5), reserialize(Suppliers.synchronizedSupplier(Suppliers.ofInstance(5))).get()); }
@Override public SystemAccessControl create(Map<String, String> config) { requireNonNull(config, "config is null"); String configFileName = config.get(SECURITY_CONFIG_FILE); checkState(configFileName != null, "Security configuration must contain the '%s' property", SECURITY_CONFIG_FILE); if (config.containsKey(SECURITY_REFRESH_PERIOD)) { Duration refreshPeriod; try { refreshPeriod = Duration.valueOf(config.get(SECURITY_REFRESH_PERIOD)); } catch (IllegalArgumentException e) { throw invalidRefreshPeriodException(config, configFileName); } if (refreshPeriod.toMillis() == 0) { throw invalidRefreshPeriodException(config, configFileName); } return ForwardingSystemAccessControl.of(memoizeWithExpiration( () -> { log.info("Refreshing system access control from %s", configFileName); return create(configFileName); }, refreshPeriod.toMillis(), MILLISECONDS)); } return create(configFileName); }
@GwtIncompatible // Thread.sleep public void testMemoizeWithExpiration() throws InterruptedException { CountingSupplier countingSupplier = new CountingSupplier(); Supplier<Integer> memoizedSupplier = Suppliers.memoizeWithExpiration(countingSupplier, 75, TimeUnit.MILLISECONDS); checkExpiration(countingSupplier, memoizedSupplier); }
@Inject @Provides public ConnectorAccessControl getConnectorAccessControl(FileBasedAccessControlConfig config) { if (config.getRefreshPeriod() != null) { return ForwardingConnectorAccessControl.of(memoizeWithExpiration( () -> { log.info("Refreshing system access control from %s", config.getConfigFile()); return new FileBasedAccessControl(config); }, config.getRefreshPeriod().toMillis(), MILLISECONDS)); } return new FileBasedAccessControl(config); } }
Supplier<NodeMap> nodeMap = Suppliers.memoizeWithExpiration(() -> { ImmutableSetMultimap.Builder<HostAddress, Node> byHostAndPort = ImmutableSetMultimap.builder(); ImmutableSetMultimap.Builder<InetAddress, Node> byHost = ImmutableSetMultimap.builder();
public static Supplier<Long> createMemoizedWithExpiration(TimelockService timelockService) { return Suppliers.memoizeWithExpiration( timelockService::getImmutableTimestamp, RELOAD_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); }
/** * Creates a supplier that returns a {@link VersionedType} containing the result of applying the given aggregating * function to a collection of values maintained in an internal map. The return value is memoized for the specified * amount of time after which a call to get() will recompute the result and increase the version of the result. * * @param aggregator the aggregating function to use. * @param expirationMillis amount of time in milliseconds after which a call to get() will recompute the result of * applying aggregator and increase the returned version. */ public AggregatingVersionedSupplier(Function<Collection<T>, T> aggregator, long expirationMillis) { this.aggregator = aggregator; this.memoizedValue = Suppliers .memoizeWithExpiration(this::recalculate, expirationMillis, TimeUnit.MILLISECONDS); }
public PermitSource(Supplier<Integer> concurrentRequestLimit) { this.concurrentRequestLimit = Suppliers.memoizeWithExpiration(concurrentRequestLimit::get, 1, TimeUnit.MINUTES);; this.concurrentRequests = new AtomicInteger(); }
private static <T> Supplier<T> memoizeWithExpiration(Supplier<T> s) { // This insanity exists to make modernizer plugin happy. We are living in the future now. return () -> Suppliers.memoizeWithExpiration(s::get, 100, TimeUnit.MILLISECONDS).get(); }
AsyncSemaphore(PermitSource permitSource, Queue<DelayedExecution<T>> requestQueue, Supplier<Integer> queueRejectionThreshold, Supplier<Exception> timeoutExceptionSupplier, boolean flushQueuePeriodically) { this.permitSource = permitSource; this.requestQueue = requestQueue; this.queueRejectionThreshold = Suppliers.memoizeWithExpiration(queueRejectionThreshold::get, 1, TimeUnit.MINUTES); this.timeoutExceptionSupplier = timeoutExceptionSupplier; if (flushQueuePeriodically) { flushingExecutor.scheduleAtFixedRate(() -> flushQueue(), 1, 1, TimeUnit.SECONDS); } }
/** * Creates a supplier such that the first call to {@link Supplier#get()} on it will take the maximum of the runtime * configuration and the persisted number of shards, and persist and memoize the result. Subsequent calls will * return the cached value until refreshTimeMillis has passed, at which point the next call will again perform the * check and set. * * @param runtimeConfig live reloadable runtime configuration for the number of shards * @param progress progress table persisting the number of shards * @param refreshTimeMillis timeout for caching the number of shards * @return supplier calculating and persisting the number of shards to use */ public static Supplier<Integer> createProgressUpdatingSupplier(Supplier<Integer> runtimeConfig, ShardProgress progress, long refreshTimeMillis) { return Suppliers.memoizeWithExpiration( () -> progress.updateNumberOfShards(runtimeConfig.get()), refreshTimeMillis, TimeUnit.MILLISECONDS); }
null, false, Duration.succinctDuration(1, MINUTES)); activeNodeCount = Suppliers.memoizeWithExpiration(() -> { String getNodeCount = "select count(*) from system.runtime.nodes where state = 'active'"; QueryResult queryResult = new PrestoQueryExecution(defaultSession, getNodeCount, false).getResult().join();
@Provides @Singleton @TimeStamp protected Supplier<Date> provideCacheBusterDate() { return memoizeWithExpiration(new Supplier<Date>() { public Date get() { return new Date(); } }, 1, TimeUnit.SECONDS); } }
/** * borrowing concurrency code to ensure that caching takes place properly */ @Provides @TimeStamp Supplier<Long> provideTimeStampCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds) { return Suppliers.memoizeWithExpiration(new Supplier<Long>() { public Long get() { return System.currentTimeMillis() / 1000; } }, seconds, TimeUnit.SECONDS); }
@Provides @Singleton @TimeStamp protected Supplier<Date> provideCacheBusterDate() { return memoizeWithExpiration(new Supplier<Date>() { public Date get() { return new Date(); } }, 1, TimeUnit.SECONDS); }
@Inject private ReturnOrFetchTemporaryUrlKeyMemoized(TemporaryUrlKeyApi client, @Named(PROPERTY_SESSION_INTERVAL) long sessionInterval) { this.delegate = Suppliers.memoizeWithExpiration( new ReturnOrFetchTemporaryUrlKey(client), sessionInterval, TimeUnit.SECONDS); }