类com.google.common.base.Ticker源码实例Demo

下面列出了怎么用com.google.common.base.Ticker的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: glowroot   文件: AggregateDaoTest.java
@Before
public void beforeEachTest() throws Exception {
    dataSource = new DataSource();
    if (dataSource.tableExists("overall_point")) {
        dataSource.execute("drop table overall_point");
    }
    if (dataSource.tableExists("transaction_point")) {
        dataSource.execute("drop table transaction_point");
    }
    cappedFile = File.createTempFile("glowroot-test-", ".capped.db");
    scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    cappedDatabase =
            new CappedDatabase(cappedFile, 1000000, scheduledExecutor, Ticker.systemTicker());
    ConfigRepositoryImpl configRepository = mock(ConfigRepositoryImpl.class);
    when(configRepository.getAdvancedConfig(AGENT_ID))
            .thenReturn(AdvancedConfig.getDefaultInstance());
    ImmutableList<RollupConfig> rollupConfigs = ImmutableList.<RollupConfig>of(
            ImmutableRollupConfig.of(1000, 0), ImmutableRollupConfig.of(15000, 3600000),
            ImmutableRollupConfig.of(900000000, 8 * 3600000));
    when(configRepository.getRollupConfigs()).thenReturn(rollupConfigs);
    aggregateDao = new AggregateDao(
            dataSource, ImmutableList.<CappedDatabase>of(cappedDatabase, cappedDatabase,
                    cappedDatabase, cappedDatabase),
            configRepository, mock(TransactionTypeDao.class), mock(FullQueryTextDao.class));
}
 
源代码2 项目: glowroot   文件: CappedDatabaseResizeTest.java
private void shouldResizeAndWrap(int newSizeKb) throws Exception {
    // when
    cappedDatabase.resize(newSizeKb);
    // because of compression, use somewhat random text and loop until wrap occurs
    String text = createRandomText();
    cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test");
    cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test");
    cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test");
    long cappedId = cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test");

    // then
    String text2 = cappedDatabase.read(cappedId).read();
    assertThat(text2).isEqualTo(text);

    // also test close and re-open
    cappedDatabase.close();
    cappedDatabase = new CappedDatabase(tempFile, 2, scheduledExecutor, Ticker.systemTicker());
    text2 = cappedDatabase.read(cappedId).read();
    assertThat(text2).isEqualTo(text);
}
 
源代码3 项目: glowroot   文件: GaugeCollectorTest.java
@Before
public void beforeEachTest() throws Exception {
    ConfigService configService = mock(ConfigService.class);
    AdvancedConfig advancedConfig =
            ImmutableAdvancedConfig.builder().mbeanGaugeNotFoundDelaySeconds(60).build();
    when(configService.getAdvancedConfig()).thenReturn(advancedConfig);

    Collector collector = mock(Collector.class);
    lazyPlatformMBeanServer = mock(LazyPlatformMBeanServer.class);
    clock = mock(Clock.class);
    ticker = mock(Ticker.class);
    logger = mock(Logger.class);
    setLogger(GaugeCollector.class, logger);
    gaugeCollector = new GaugeCollector(configService, collector, lazyPlatformMBeanServer,
            null, clock, ticker);
}
 
源代码4 项目: presto   文件: Backoff.java
@VisibleForTesting
public Backoff(int minTries, Duration maxFailureInterval, Ticker ticker, List<Duration> backoffDelayIntervals)
{
    checkArgument(minTries > 0, "minTries must be at least 1");
    requireNonNull(maxFailureInterval, "maxFailureInterval is null");
    requireNonNull(ticker, "ticker is null");
    requireNonNull(backoffDelayIntervals, "backoffDelayIntervals is null");
    checkArgument(!backoffDelayIntervals.isEmpty(), "backoffDelayIntervals must contain at least one entry");

    this.minTries = minTries;
    this.maxFailureIntervalNanos = maxFailureInterval.roundTo(NANOSECONDS);
    this.ticker = ticker;
    this.backoffDelayIntervalsNanos = backoffDelayIntervals.stream()
            .mapToLong(duration -> duration.roundTo(NANOSECONDS))
            .toArray();
}
 
源代码5 项目: glowroot   文件: Weaver.java
public Weaver(Supplier<List<Advice>> advisors, List<ShimType> shimTypes,
        List<MixinType> mixinTypes, AnalyzedWorld analyzedWorld,
        TransactionRegistry transactionRegistry, Ticker ticker, TimerNameCache timerNameCache,
        final ConfigService configService) {
    this.advisors = advisors;
    this.shimTypes = ImmutableList.copyOf(shimTypes);
    this.mixinTypes = ImmutableList.copyOf(mixinTypes);
    this.analyzedWorld = analyzedWorld;
    this.transactionRegistry = transactionRegistry;
    this.ticker = ticker;
    configService.addConfigListener(new ConfigListener() {
        @Override
        public void onChange() {
            weavingTimerEnabled = configService.getAdvancedConfig().weavingTimer();
        }
    });
    this.timerName = timerNameCache.getTimerName(OnlyForTheTimerName.class);
}
 
源代码6 项目: presto   文件: TestSqlTask.java
public TestSqlTask()
{
    taskExecutor = new TaskExecutor(8, 16, 3, 4, Ticker.systemTicker());
    taskExecutor.start();

    taskNotificationExecutor = newScheduledThreadPool(10, threadsNamed("task-notification-%s"));
    driverYieldExecutor = newScheduledThreadPool(2, threadsNamed("driver-yield-%s"));

    LocalExecutionPlanner planner = createTestingPlanner();

    sqlTaskExecutionFactory = new SqlTaskExecutionFactory(
            taskNotificationExecutor,
            taskExecutor,
            planner,
            createTestSplitMonitor(),
            new TaskManagerConfig());
}
 
源代码7 项目: Velocity   文件: GuavaCacheRatelimiterTest.java
@Test
void attemptOne() {
  long base = System.nanoTime();
  AtomicLong extra = new AtomicLong();
  Ticker testTicker = new Ticker() {
    @Override
    public long read() {
      return base + extra.get();
    }
  };
  Ratelimiter ratelimiter = new GuavaCacheRatelimiter(1000, TimeUnit.MILLISECONDS, testTicker);
  assertTrue(ratelimiter.attempt(InetAddress.getLoopbackAddress()));
  assertFalse(ratelimiter.attempt(InetAddress.getLoopbackAddress()));
  extra.addAndGet(TimeUnit.SECONDS.toNanos(2));
  assertTrue(ratelimiter.attempt(InetAddress.getLoopbackAddress()));
}
 
源代码8 项目: drift   文件: DriftMethodHandler.java
public ListenableFuture<Object> invoke(Optional<String> addressSelectionContext, Map<String, String> headers, List<Object> parameters)
{
    if (!headerParameters.isEmpty()) {
        headers = new LinkedHashMap<>(headers);
        for (Entry<Integer, ThriftHeaderParameter> entry : headerParameters.entrySet()) {
            String headerValue = (String) parameters.get(entry.getKey());
            if (headerValue != null) {
                headers.put(entry.getValue().getName(), headerValue);
            }
        }

        ImmutableList.Builder<Object> newParameters = ImmutableList.builder();
        for (int index = 0; index < parameters.size(); index++) {
            if (!headerParameters.containsKey(index)) {
                newParameters.add(parameters.get(index));
            }
        }
        parameters = newParameters.build();
    }
    return createDriftMethodInvocation(invoker, metadata, headers, parameters, retryPolicy, addressSelector, addressSelectionContext, stat, Ticker.systemTicker());
}
 
源代码9 项目: drift   文件: DriftMethodInvocation.java
static <A extends Address> DriftMethodInvocation<A> createDriftMethodInvocation(
        MethodInvoker invoker,
        MethodMetadata metadata,
        Map<String, String> headers,
        List<Object> parameters,
        RetryPolicy retryPolicy,
        AddressSelector<A> addressSelector,
        Optional<String> addressSelectionContext,
        MethodInvocationStat stat,
        Ticker ticker)
{
    DriftMethodInvocation<A> invocation = new DriftMethodInvocation<>(
            invoker,
            metadata,
            headers,
            parameters,
            retryPolicy,
            addressSelector,
            addressSelectionContext,
            stat,
            ticker);
    // invocation can not be started from constructor, because it may start threads that can call back into the unpublished object
    invocation.nextAttempt(true);
    return invocation;
}
 
源代码10 项目: drift   文件: TestDriftMethodInvocation.java
private static DriftMethodInvocation<?> createDriftMethodInvocation(
        RetryPolicy retryPolicy,
        TestingMethodInvocationStat stat,
        MockMethodInvoker invoker,
        AddressSelector<?> addressSelector,
        Ticker ticker)
{
    return DriftMethodInvocation.createDriftMethodInvocation(
            invoker,
            METHOD_METADATA,
            ImmutableMap.of(),
            ImmutableList.of(),
            retryPolicy,
            addressSelector,
            Optional.empty(),
            stat,
            ticker);
}
 
源代码11 项目: dremio-oss   文件: TestDatasetVersion.java
@Test
public void testUniqueness() {
  Ticker ticker = new Ticker() {
    private final long millis = System.currentTimeMillis();

    @Override
    public long read() {
      return millis;
    }
  };

  DatasetVersion version1 = DatasetVersion.forTesting(ticker);
  DatasetVersion version2 = DatasetVersion.forTesting(ticker);

  assertNotEquals(version1, version2);
}
 
源代码12 项目: bazel-buildfarm   文件: LocalCache.java
private ManualSerializationProxy(
    Strength keyStrength,
    Strength valueStrength,
    Equivalence<Object> keyEquivalence,
    Equivalence<Object> valueEquivalence,
    long expireAfterWriteNanos,
    long expireAfterAccessNanos,
    long maxWeight,
    Weigher<K, V> weigher,
    int concurrencyLevel,
    RemovalListener<? super K, ? super V> removalListener,
    Ticker ticker,
    CacheLoader<? super K, V> loader) {
  this.keyStrength = keyStrength;
  this.valueStrength = valueStrength;
  this.keyEquivalence = keyEquivalence;
  this.valueEquivalence = valueEquivalence;
  this.expireAfterWriteNanos = expireAfterWriteNanos;
  this.expireAfterAccessNanos = expireAfterAccessNanos;
  this.maxWeight = maxWeight;
  this.weigher = weigher;
  this.concurrencyLevel = concurrencyLevel;
  this.removalListener = removalListener;
  this.ticker = (ticker == Ticker.systemTicker() || ticker == NULL_TICKER) ? null : ticker;
  this.loader = loader;
}
 
源代码13 项目: rubix   文件: BookKeeper.java
@VisibleForTesting
BookKeeper(Configuration conf, BookKeeperMetrics bookKeeperMetrics, Ticker ticker) throws FileNotFoundException
{
  this.conf = conf;
  this.bookKeeperMetrics = bookKeeperMetrics;
  this.metrics = bookKeeperMetrics.getMetricsRegistry();
  this.ticker = ticker;
  initializeMetrics();
  initializeCache(conf, ticker);
  cleanupOldCacheFiles(conf);

  fetchProcessor = null;
  if (CacheConfig.isParallelWarmupEnabled(conf)) {
    fetchProcessor = new RemoteFetchProcessor(this, metrics, conf);
  }
}
 
源代码14 项目: distributedlog   文件: BKSyncLogReader.java
private void startReadAhead(DLSN startDLSN) throws IOException {
    readAheadReader = new ReadAheadEntryReader(
                bkdlm.getStreamName(),
                startDLSN,
                bkdlm.getConf(),
                readHandler,
                bkdlm.getReaderEntryStore(),
                bkdlm.getScheduler(),
                Ticker.systemTicker(),
                bkdlm.alertStatsLogger);
    readHandler.registerListener(readAheadReader);
    readHandler.asyncStartFetchLogSegments()
            .thenApply(logSegments -> {
                readAheadReader.addStateChangeNotification(BKSyncLogReader.this);
                readAheadReader.start(logSegments.getValue());
                return null;
            });
}
 
@Test
public void testRespectsTime() throws Exception {
    final long startTime = System.nanoTime();
    final AtomicLong currentTime = new AtomicLong(startTime);
    Ticker ticker = new Ticker() {
        @Override public long read() {
            return currentTime.get();
        }
    };
    ProportionalZoneFailureDetector detector = new ProportionalZoneFailureDetector(2, Duration.ONE_HOUR, 0.9, ticker);

    for (int i = 0; i < 2; i++) {
        detector.onStartupFailure(loc1, entity1, new Throwable("simulated failure"));
    }
    assertTrue(detector.hasFailed(loc1));
    
    currentTime.set(startTime + TimeUnit.MILLISECONDS.toNanos(1000*60*60 - 1));
    assertTrue(detector.hasFailed(loc1));

    currentTime.set(startTime + TimeUnit.MILLISECONDS.toNanos(1000*60*60 + 1));
    assertFalse(detector.hasFailed(loc1));
}
 
public void setUp() throws Exception {
    if (sharedTime==null)
        currentTime = new AtomicLong(System.currentTimeMillis());
    
    ticker = new Ticker() {
        // strictly not a ticker because returns millis UTC, but it works fine even so
        @Override public long read() {
            if (sharedTime!=null) return sharedTime.get();
            return currentTime.get();
        }
    };
    
    nodeName = "node "+nodes.size();
    mgmt = newLocalManagementContext();
    ownNodeId = mgmt.getManagementNodeId();
    objectStore = new ListeningObjectStore(newPersistenceObjectStore());
    objectStore.injectManagementContext(mgmt);
    objectStore.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
    persister = new ManagementPlaneSyncRecordPersisterToObjectStore(mgmt, objectStore, classLoader);
    ((ManagementPlaneSyncRecordPersisterToObjectStore)persister).preferRemoteTimestampInMemento();
    BrooklynMementoPersisterToObjectStore persisterObj = new BrooklynMementoPersisterToObjectStore(objectStore, mgmt, classLoader);
    mgmt.getRebindManager().setPersister(persisterObj, PersistenceExceptionHandlerImpl.builder().build());
    ha = ((HighAvailabilityManagerImpl)mgmt.getHighAvailabilityManager())
        .setPollPeriod(Duration.PRACTICALLY_FOREVER)
        .setHeartbeatTimeout(Duration.THIRTY_SECONDS)
        .setLocalTicker(ticker)
        .setRemoteTicker(ticker)
        .setPersister(persister);
    log.info("Created "+nodeName+" "+ownNodeId);
}
 
源代码17 项目: glowroot   文件: Tickers.java
@VisibleForTesting
static Ticker getTicker(boolean dummyTicker) {
    if (dummyTicker) {
        return new DummyTicker();
    } else {
        return Ticker.systemTicker();
    }
}
 
源代码18 项目: presto   文件: FileBasedNetworkTopology.java
@Inject
public FileBasedNetworkTopology(TopologyFileConfig topologyConfig)
{
    this(
            requireNonNull(topologyConfig, "topologyConfig is null").getNetworkTopologyFile(),
            topologyConfig.getRefreshPeriod(),
            Ticker.systemTicker());
}
 
源代码19 项目: presto   文件: FileBasedNetworkTopology.java
FileBasedNetworkTopology(File networkTopologyFile, Duration refreshPeriod, Ticker ticker)
{
    this.networkTopologyFile = requireNonNull(networkTopologyFile, "networkTopologyFile is null");
    this.refreshPeriodNanos = requireNonNull(refreshPeriod, "refreshPeriodNanos is null").roundTo(NANOSECONDS);
    this.ticker = requireNonNull(ticker, "ticker is null");
    refreshTopology();
}
 
源代码20 项目: glowroot   文件: WeaverTest.java
@Test
public void shouldStillCallOnAfterOfHigherPriorityPointcut() throws Exception {
    // given

    // SomeAspectThreadLocals is passed as bridgeable so that the static thread locals will be
    // accessible for test verification
    IsolatedWeavingClassLoader isolatedWeavingClassLoader = new IsolatedWeavingClassLoader(
            Misc.class, SomeAspectThreadLocals.class, IntegerThreadLocal.class);
    List<Advice> advisors = Lists.newArrayList();
    advisors.add(newAdvice(BasicAdvice.class));
    advisors.add(newAdvice(BindThrowableAdvice.class));
    advisors.add(newAdvice(ThrowInOnBeforeAdvice.class));
    advisors.add(newAdvice(BasicHighOrderAdvice.class));
    Supplier<List<Advice>> advisorsSupplier =
            Suppliers.<List<Advice>>ofInstance(ImmutableList.copyOf(advisors));
    AnalyzedWorld analyzedWorld = new AnalyzedWorld(advisorsSupplier,
            ImmutableList.<ShimType>of(), ImmutableList.<MixinType>of(), null);
    TransactionRegistry transactionRegistry = mock(TransactionRegistry.class);
    when(transactionRegistry.getCurrentThreadContextHolder())
            .thenReturn(new ThreadContextThreadLocal().getHolder());
    Weaver weaver = new Weaver(advisorsSupplier, ImmutableList.<ShimType>of(),
            ImmutableList.<MixinType>of(), analyzedWorld, transactionRegistry,
            Ticker.systemTicker(), new TimerNameCache(), mock(ConfigService.class));
    isolatedWeavingClassLoader.setWeaver(weaver);
    Misc test = isolatedWeavingClassLoader.newInstance(BasicMisc.class, Misc.class);
    // when
    RuntimeException exception = null;
    try {
        test.execute1();
    } catch (RuntimeException e) {
        exception = e;
    }
    // then
    assertThat(exception.getMessage()).isEqualTo("Abxy");
    assertThat(SomeAspectThreadLocals.onBeforeCount.get()).isEqualTo(1);
    assertThat(SomeAspectThreadLocals.onReturnCount.get()).isEqualTo(0);
    assertThat(SomeAspectThreadLocals.onThrowCount.get()).isEqualTo(2);
    assertThat(SomeAspectThreadLocals.onAfterCount.get()).isEqualTo(1);
    assertThat(SomeAspectThreadLocals.throwable.get().getMessage()).isEqualTo("Abxy");
}
 
源代码21 项目: multiway-pool   文件: TimeToIdlePolicy.java
TimeToIdlePolicy(long expireAfterAccessNanos,
    Ticker ticker, EvictionListener<K> evictionListener) {
  this.ticker = ticker;
  this.idleLock = new ReentrantLock();
  this.idleQueue = new LinkedDeque<>();
  this.taskStack = new EliminationStack<>();
  this.expireAfterAccessNanos = expireAfterAccessNanos;
  this.evictionListener = checkNotNull(evictionListener);
}
 
源代码22 项目: presto   文件: QueryStateMachine.java
static QueryStateMachine beginWithTicker(
        String query,
        Optional<String> preparedQuery,
        Session session,
        URI self,
        ResourceGroupId resourceGroup,
        boolean transactionControl,
        TransactionManager transactionManager,
        AccessControl accessControl,
        Executor executor,
        Ticker ticker,
        Metadata metadata,
        WarningCollector warningCollector)
{
    // If there is not an existing transaction, begin an auto commit transaction
    if (session.getTransactionId().isEmpty() && !transactionControl) {
        // TODO: make autocommit isolation level a session parameter
        TransactionId transactionId = transactionManager.beginTransaction(true);
        session = session.beginTransactionId(transactionId, transactionManager, accessControl);
    }

    QueryStateMachine queryStateMachine = new QueryStateMachine(
            query,
            preparedQuery,
            session,
            self,
            resourceGroup,
            transactionManager,
            executor,
            ticker,
            metadata,
            warningCollector);
    queryStateMachine.addStateChangeListener(newState -> QUERY_STATE_LOG.debug("Query %s is %s", queryStateMachine.getQueryId(), newState));

    return queryStateMachine;
}
 
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    currentTime = new AtomicLong(1000000000L);
    ticker = new Ticker() {
        // strictly not a ticker because returns millis UTC, but it works fine even so
        @Override public long read() {
            return currentTime.get();
        }
    };
    stateListener = new RecordingManagementNodeStateListener();
    promotionListener = new RecordingPromotionListener();
    managementContext = newLocalManagementContext();
    ownNodeId = managementContext.getManagementNodeId();
    objectStore = newPersistenceObjectStore();
    objectStore.injectManagementContext(managementContext);
    objectStore.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
    persister = new ManagementPlaneSyncRecordPersisterToObjectStore(managementContext, objectStore, classLoader);
    ((ManagementPlaneSyncRecordPersisterToObjectStore)persister).preferRemoteTimestampInMemento();
    BrooklynMementoPersisterToObjectStore persisterObj = new BrooklynMementoPersisterToObjectStore(
            objectStore, 
            managementContext, 
            classLoader);
    managementContext.getRebindManager().setPersister(persisterObj, PersistenceExceptionHandlerImpl.builder().build());
    manager = ((HighAvailabilityManagerImpl)managementContext.getHighAvailabilityManager())
            .setPollPeriod(getPollPeriod())
            .setHeartbeatTimeout(Duration.THIRTY_SECONDS)
            .setPromotionListener(promotionListener)
            .setLocalTicker(ticker)
            .setRemoteTicker(getRemoteTicker())
            .setPersister(persister);
    persister.delta(ManagementPlaneSyncRecordDeltaImpl.builder()
        .node(newManagerMemento(ownNodeId, ManagementNodeState.HOT_STANDBY))
        .build());

}
 
源代码24 项目: codebuff   文件: LocalCache.java
private ManualSerializationProxy(Strength keyStrength, Strength valueStrength, Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence, long expireAfterWriteNanos, long expireAfterAccessNanos, long maxWeight, Weigher<K, V> weigher, int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener, Ticker ticker, CacheLoader<? super K, V> loader) {
  this.keyStrength = keyStrength;
  this.valueStrength = valueStrength;
  this.keyEquivalence = keyEquivalence;
  this.valueEquivalence = valueEquivalence;
  this.expireAfterWriteNanos = expireAfterWriteNanos;
  this.expireAfterAccessNanos = expireAfterAccessNanos;
  this.maxWeight = maxWeight;
  this.weigher = weigher;
  this.concurrencyLevel = concurrencyLevel;
  this.removalListener = removalListener;
  this.ticker = (ticker == Ticker.systemTicker() || ticker == NULL_TICKER) ? null : ticker;
  this.loader = loader;
}
 
源代码25 项目: glowroot   文件: CappedDatabaseOutputStreamTest.java
@Before
public void onBefore() throws IOException {
    tempFile = File.createTempFile("glowroot-test-", ".capped.txt");
    scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    cappedOut = CappedDatabaseOutputStream.create(tempFile, 10, scheduledExecutor,
            Ticker.systemTicker());
    in = new RandomAccessFile(tempFile, "r");
}
 
源代码26 项目: streaminer   文件: Rate.java
public Rate(int windowSize, double scaleFactor, Ticker ticker) {
    if (scaleFactor == 0)
        throw new IllegalArgumentException("Scale factor must be non-zero!");
    
    this.ticker = ticker;
    this.scaleFactor = scaleFactor;
    samples = new LinkedBlockingDeque<Pair<Long, Double>>(windowSize);
}
 
源代码27 项目: blueflood   文件: ShardStateManagerTest.java
@Before
public void setup() {
    ShardStateManager shardStateManager = new ShardStateManager(managedShards, Ticker.systemTicker(), mockClock);
    slotStateManager = shardStateManager.getSlotStateManager(TEST_SHARD, TEST_GRANULARITY);

    when(mockClock.now()).thenReturn(new Instant(lastIngestTime));
}
 
源代码28 项目: presto   文件: ShardCleaner.java
public ShardCleaner(
        DaoSupplier<ShardDao> shardDaoSupplier,
        String currentNode,
        boolean coordinator,
        Ticker ticker,
        StorageService storageService,
        Optional<BackupStore> backupStore,
        Duration maxTransactionAge,
        Duration transactionCleanerInterval,
        Duration localCleanerInterval,
        Duration localCleanTime,
        Duration backupCleanerInterval,
        Duration backupCleanTime,
        int backupDeletionThreads,
        Duration maxCompletedTransactionAge)
{
    this.dao = shardDaoSupplier.onDemand();
    this.currentNode = requireNonNull(currentNode, "currentNode is null");
    this.coordinator = coordinator;
    this.ticker = requireNonNull(ticker, "ticker is null");
    this.storageService = requireNonNull(storageService, "storageService is null");
    this.backupStore = requireNonNull(backupStore, "backupStore is null");
    this.maxTransactionAge = requireNonNull(maxTransactionAge, "maxTransactionAge");
    this.transactionCleanerInterval = requireNonNull(transactionCleanerInterval, "transactionCleanerInterval is null");
    this.localCleanerInterval = requireNonNull(localCleanerInterval, "localCleanerInterval is null");
    this.localCleanTime = requireNonNull(localCleanTime, "localCleanTime is null");
    this.backupCleanerInterval = requireNonNull(backupCleanerInterval, "backupCleanerInterval is null");
    this.backupCleanTime = requireNonNull(backupCleanTime, "backupCleanTime is null");
    this.scheduler = newScheduledThreadPool(2, daemonThreadsNamed("shard-cleaner-%s"));
    this.backupExecutor = newFixedThreadPool(backupDeletionThreads, daemonThreadsNamed("shard-cleaner-backup-%s"));
    this.maxCompletedTransactionAge = requireNonNull(maxCompletedTransactionAge, "maxCompletedTransactionAge is null");
}
 
源代码29 项目: attic-aurora   文件: BiCache.java
@Inject
public BiCache(
    StatsProvider statsProvider,
    BiCacheSettings settings,
    final Clock clock) {

  requireNonNull(clock);
  this.cache = CacheBuilder.newBuilder()
      .expireAfterWrite(settings.expireAfter.as(Time.MINUTES), TimeUnit.MINUTES)
      .ticker(new Ticker() {
        @Override
        public long read() {
          return clock.nowNanos();
        }
      })
      .removalListener(new RemovalListener<K, V>() {
        @Override
        public void onRemoval(RemovalNotification<K, V> notification) {
          removalCounter.getAndIncrement();
          if (notification.wasEvicted()) {
            expirationCounter.incrementAndGet();
          }
          inverse.remove(notification.getValue(), notification.getKey());
        }
      })
      .build();

  statsProvider.makeGauge(settings.cacheName + "_cache_size", cache::size);
  removalCounter = statsProvider.makeCounter(settings.cacheName + "_cache_removals");
  expirationCounter = statsProvider.makeCounter(
      settings.cacheName + "_cache_expiration_removals");
  explictRemovalCounter = statsProvider.makeCounter(
      settings.cacheName + "_cache_explicit_removals");
}
 
源代码30 项目: presto   文件: AssignmentLimiter.java
public AssignmentLimiter(NodeSupplier nodeSupplier, Ticker ticker, Duration reassignmentDelay, Duration reassignmentInterval)
{
    this.nodeSupplier = requireNonNull(nodeSupplier, "nodeSupplier is null");
    this.ticker = requireNonNull(ticker, "ticker is null");
    this.reassignmentDelay = requireNonNull(reassignmentDelay, "reassignmentDelay is null");
    this.reassignmentInterval = requireNonNull(reassignmentInterval, "reassignmentInterval is null");
}