Java Code Examples for com.google.common.base.Ticker#systemTicker()

The following examples show how to use com.google.common.base.Ticker#systemTicker() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OfferManagerModule.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
OfferSettings provideOfferSettings(OfferSet offerSet) {
  // We have a dual eviction strategy for the static ban cache in OfferManager that is based on
  // both maximum size of the cache and the length an offer is valid. We do this in order to
  // satisfy requirements in both single- and multi-framework environments. If offers are held for
  // a finite duration, then we can expire cache entries after offerMaxHoldTime since that is the
  // longest it will be valid for. Additionally, cluster operators will most likely not have to
  // worry about cache size in this case as this behavior mimics current behavior. If offers are
  // held indefinitely, then we never expire cache entries but the cluster operator can specify a
  // maximum size to avoid a memory leak.
  long maxOfferHoldTime;
  if (cliOptions.offer.holdOffersForever) {
    maxOfferHoldTime = Long.MAX_VALUE;
  } else {
    maxOfferHoldTime = cliOptions.offer.minOfferHoldTime.as(Time.SECONDS)
        + cliOptions.offer.offerHoldJitterWindow.as(Time.SECONDS);
  }

  return new OfferSettings(
      cliOptions.offer.offerFilterDuration,
      offerSet,
      Amount.of(maxOfferHoldTime, Time.SECONDS),
      cliOptions.offer.offerStaticBanCacheMaxSize,
      Ticker.systemTicker());
}
 
Example 2
Source File: TestSqlTask.java    From presto with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 3
Source File: LocalCache.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: WeaverTest.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public static <S, T extends S> S newWovenObject(Class<T> implClass, Class<S> bridgeClass,
        Class<?> adviceOrShimOrMixinClass, Class<?>... extraBridgeClasses) throws Exception {
    // SomeAspectThreadLocals is passed as bridgeable so that the static thread locals will be
    // accessible for test verification
    List<Class<?>> bridgeClasses = Lists.newArrayList();
    bridgeClasses.add(bridgeClass);
    bridgeClasses.add(SomeAspectThreadLocals.class);
    bridgeClasses.add(IntegerThreadLocal.class);
    bridgeClasses.addAll(Arrays.asList(extraBridgeClasses));
    IsolatedWeavingClassLoader isolatedWeavingClassLoader =
            new IsolatedWeavingClassLoader(bridgeClasses.toArray(new Class<?>[0]));
    List<Advice> advisors = Lists.newArrayList();
    if (adviceOrShimOrMixinClass.isAnnotationPresent(Pointcut.class)) {
        advisors.add(newAdvice(adviceOrShimOrMixinClass));
    }
    List<MixinType> mixinTypes = Lists.newArrayList();
    Mixin mixin = adviceOrShimOrMixinClass.getAnnotation(Mixin.class);
    if (mixin != null) {
        mixinTypes.add(newMixin(adviceOrShimOrMixinClass));
    }
    List<ShimType> shimTypes = Lists.newArrayList();
    Shim shim = adviceOrShimOrMixinClass.getAnnotation(Shim.class);
    if (shim != null) {
        shimTypes.add(ShimType.create(shim, adviceOrShimOrMixinClass));
    }
    Supplier<List<Advice>> advisorsSupplier =
            Suppliers.<List<Advice>>ofInstance(ImmutableList.copyOf(advisors));
    AnalyzedWorld analyzedWorld =
            new AnalyzedWorld(advisorsSupplier, shimTypes, mixinTypes, null);
    TransactionRegistry transactionRegistry = mock(TransactionRegistry.class);
    when(transactionRegistry.getCurrentThreadContextHolder())
            .thenReturn(new ThreadContextThreadLocal().getHolder());
    Weaver weaver = new Weaver(advisorsSupplier, shimTypes, mixinTypes, analyzedWorld,
            transactionRegistry, Ticker.systemTicker(), new TimerNameCache(),
            mock(ConfigService.class));
    isolatedWeavingClassLoader.setWeaver(weaver);
    return isolatedWeavingClassLoader.newInstance(implClass, bridgeClass);
}
 
Example 5
Source File: HttpRemoteTask.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Backoff createCleanupBackoff()
{
    return new Backoff(10, new Duration(10, TimeUnit.MINUTES), Ticker.systemTicker(), ImmutableList.<Duration>builder()
            .add(new Duration(0, MILLISECONDS))
            .add(new Duration(100, MILLISECONDS))
            .add(new Duration(500, MILLISECONDS))
            .add(new Duration(1, SECONDS))
            .add(new Duration(10, SECONDS))
            .build());
}
 
Example 6
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
}
 
Example 7
Source File: TraceDaoTest.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    dataSource = new DataSource();
    if (dataSource.tableExists("trace")) {
        dataSource.execute("drop table trace");
    }
    cappedFile = File.createTempFile("glowroot-test-", ".capped.db");
    scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    cappedDatabase =
            new CappedDatabase(cappedFile, 1000000, scheduledExecutor, Ticker.systemTicker());
    traceDao = new TraceDao(dataSource, cappedDatabase, mock(TransactionTypeDao.class),
            mock(FullQueryTextDao.class), mock(TraceAttributeNameDao.class));
}
 
Example 8
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
}
 
Example 9
Source File: PlanCompiledProgram.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Override
public ProgramResult run(Map<String, Object> arguments, boolean debug, ExecutionScope inputScope, long timeout, TimeUnit timeoutUnit) throws Exception {
    TimeoutTracker tracker = new TimeoutTracker(timeout, timeoutUnit, new RelativeTicker(Ticker.systemTicker()));
    ProgramTracer tracer = new ProgramTracer(Ticker.systemTicker(), debug, "program", name);
    scoper.enter(new ScopedObjects(inputScope));
    TaskMetricEmitter requestEmitter = injector.getInstance(TaskMetricEmitter.class);
    TaskContext context = new TaskContext(requestEmitter, tracer, tracker);
    PlanProgramResultAdapter adapter = new PlanProgramResultAdapter(tracer, resultSetInfos, scoper);
    invoke(adapter, arguments, inputScope, context);
    requestEmitter.end();
    scoper.exit();
    return adapter;
}
 
Example 10
Source File: CacheBuilder.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
Ticker getTicker(boolean recordsTime) {
  if (ticker != null) {
    return ticker;
  }
  return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
}
 
Example 11
Source File: CappedDatabaseResizeTest.java    From glowroot with Apache License 2.0 4 votes vote down vote up
@Before
public void onBefore() throws IOException {
    tempFile = File.createTempFile("glowroot-test-", ".capped.db");
    scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    cappedDatabase = new CappedDatabase(tempFile, 2, scheduledExecutor, Ticker.systemTicker());
}
 
Example 12
Source File: CacheBuilder.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
Ticker getTicker(boolean recordsTime) {
  if (ticker != null) {
    return ticker;
  }
  return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
}
 
Example 13
Source File: BufferedCancelIndicator.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Buffer the cancellation attempts that are issued by the given delegate.
 */
public BufferedCancelIndicator(CancelIndicator delegate, Duration buffer) {
	this(delegate, buffer, Ticker.systemTicker());
}
 
Example 14
Source File: GuavaCacheRatelimiter.java    From Velocity with MIT License 4 votes vote down vote up
GuavaCacheRatelimiter(long time, TimeUnit unit) {
  this(time, unit, Ticker.systemTicker());
}
 
Example 15
Source File: BKAsyncLogReader.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
/**
 * Read up to <i>numEntries</i> entries. The future will be satisfied when any number of entries are
 * ready (1 to <i>numEntries</i>).
 *
 * @param numEntries
 *          num entries to read
 * @return A promise that satisfied with a non-empty list of log records with their DLSN.
 */
private synchronized CompletableFuture<List<LogRecordWithDLSN>> readInternal(int numEntries,
                                                                  long deadlineTime,
                                                                  TimeUnit deadlineTimeUnit) {
    timeBetweenReadNexts.registerSuccessfulEvent(
        readNextDelayStopwatch.elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
    readNextDelayStopwatch.reset().start();
    final PendingReadRequest readRequest = new PendingReadRequest(numEntries, deadlineTime, deadlineTimeUnit);

    if (null == readAheadReader) {
        final ReadAheadEntryReader readAheadEntryReader = this.readAheadReader = new ReadAheadEntryReader(
                getStreamName(),
                getStartDLSN(),
                bkDistributedLogManager.getConf(),
                readHandler,
                bkDistributedLogManager.getReaderEntryStore(),
                bkDistributedLogManager.getScheduler(),
                Ticker.systemTicker(),
                bkDistributedLogManager.alertStatsLogger);
        readHandler.checkLogStreamExists().whenComplete(new FutureEventListener<Void>() {
            @Override
            public void onSuccess(Void value) {
                try {
                    readHandler.registerListener(readAheadEntryReader);
                    readHandler.asyncStartFetchLogSegments()
                            .thenAccept(logSegments -> {
                                readAheadEntryReader.addStateChangeNotification(BKAsyncLogReader.this);
                                readAheadEntryReader.start(logSegments.getValue());
                            });
                } catch (Exception exc) {
                    notifyOnError(exc);
                }
            }

            @Override
            public void onFailure(Throwable cause) {
                notifyOnError(cause);
            }
        });
    }

    if (checkClosedOrInError("readNext")) {
        readRequest.completeExceptionally(lastException.get());
    } else {
        boolean queueEmpty = pendingRequests.isEmpty();
        pendingRequests.add(readRequest);

        if (queueEmpty) {
            scheduleBackgroundRead();
        }
    }

    readNextExecTime.registerSuccessfulEvent(
        readNextDelayStopwatch.elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
    readNextDelayStopwatch.reset().start();

    return readRequest.getPromise();
}
 
Example 16
Source File: BKLogReadHandler.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
/**
 * Construct a Bookkeeper journal manager.
 */
public BKLogReadHandler(ZKLogMetadataForReader logMetadata,
                        Optional<String> subscriberId,
                        DistributedLogConfiguration conf,
                        DynamicDistributedLogConfiguration dynConf,
                        ZooKeeperClientBuilder zkcBuilder,
                        BookKeeperClientBuilder bkcBuilder,
                        LogSegmentMetadataStore metadataStore,
                        OrderedScheduler scheduler,
                        OrderedScheduler lockStateExecutor,
                        OrderedScheduler readAheadExecutor,
                        AlertStatsLogger alertStatsLogger,
                        ReadAheadExceptionsLogger readAheadExceptionsLogger,
                        StatsLogger statsLogger,
                        StatsLogger perLogStatsLogger,
                        String clientId,
                        AsyncNotification notification,
                        boolean isHandleForReading,
                        boolean deserializeRecordSet) {
    super(logMetadata, conf, zkcBuilder, bkcBuilder, metadataStore, scheduler,
          statsLogger, alertStatsLogger, notification, LogSegmentFilter.DEFAULT_FILTER, clientId);
    this.logMetadataForReader = logMetadata;
    this.dynConf = dynConf;
    this.readAheadExecutor = readAheadExecutor;
    this.alertStatsLogger = alertStatsLogger;
    this.perLogStatsLogger =
            isHandleForReading ? perLogStatsLogger : NullStatsLogger.INSTANCE;
    this.handlerStatsLogger =
            BroadCastStatsLogger.masterslave(this.perLogStatsLogger, statsLogger);
    this.readAheadExceptionsLogger = readAheadExceptionsLogger;

    handleCache = LedgerHandleCache.newBuilder()
            .bkc(this.bookKeeperClient)
            .conf(conf)
            .statsLogger(statsLogger)
            .build();
    readAheadCache = new ReadAheadCache(
            getFullyQualifiedName(),
            handlerStatsLogger,
            alertStatsLogger,
            notification,
            dynConf.getReadAheadMaxRecords(),
            deserializeRecordSet,
            conf.getTraceReadAheadDeliveryLatency(),
            conf.getDataLatencyWarnThresholdMillis(),
            Ticker.systemTicker());

    this.subscriberId = subscriberId;
    this.readLockPath = logMetadata.getReadLockPath(subscriberId);
    this.lockStateExecutor = lockStateExecutor;
    this.lockFactory = new ZKSessionLockFactory(
            zooKeeperClient,
            getLockClientId(),
            lockStateExecutor,
            conf.getZKNumRetries(),
            conf.getLockTimeoutMilliSeconds(),
            conf.getZKRetryBackoffStartMillis(),
            statsLogger.scope("read_lock"));

    this.isHandleForReading = isHandleForReading;
}
 
Example 17
Source File: RateLimiter.java    From kite with Apache License 2.0 4 votes vote down vote up
Stopwatch() {
  this.ticker = Ticker.systemTicker();
}
 
Example 18
Source File: BufferedCancelIndicator.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Buffer the cancellation attempts that are issued by the given delegate.
 */
public BufferedCancelIndicator(CancelIndicator delegate) {
	this(delegate, Ticker.systemTicker(), ONE_SECOND);
}
 
Example 19
Source File: WeaverTest.java    From glowroot with Apache License 2.0 4 votes vote down vote up
public static <S, T extends S> S newWovenObject(LazyDefinedClass toBeDefinedImplClass,
        Class<S> bridgeClass, Class<?> adviceOrShimOrMixinClass, Class<?>... extraBridgeClasses)
        throws Exception {
    // SomeAspectThreadLocals is passed as bridgeable so that the static thread locals will be
    // accessible for test verification
    List<Class<?>> bridgeClasses = Lists.newArrayList();
    bridgeClasses.add(bridgeClass);
    bridgeClasses.add(SomeAspectThreadLocals.class);
    bridgeClasses.add(IntegerThreadLocal.class);
    bridgeClasses.addAll(Arrays.asList(extraBridgeClasses));
    IsolatedWeavingClassLoader isolatedWeavingClassLoader =
            new IsolatedWeavingClassLoader(bridgeClasses.toArray(new Class<?>[0]));
    List<Advice> advisors = Lists.newArrayList();
    if (adviceOrShimOrMixinClass.isAnnotationPresent(Pointcut.class)) {
        advisors.add(newAdvice(adviceOrShimOrMixinClass));
    }
    List<MixinType> mixinTypes = Lists.newArrayList();
    Mixin mixin = adviceOrShimOrMixinClass.getAnnotation(Mixin.class);
    if (mixin != null) {
        mixinTypes.add(newMixin(adviceOrShimOrMixinClass));
    }
    List<ShimType> shimTypes = Lists.newArrayList();
    Shim shim = adviceOrShimOrMixinClass.getAnnotation(Shim.class);
    if (shim != null) {
        shimTypes.add(ShimType.create(shim, adviceOrShimOrMixinClass));
    }
    Supplier<List<Advice>> advisorsSupplier =
            Suppliers.<List<Advice>>ofInstance(ImmutableList.copyOf(advisors));
    AnalyzedWorld analyzedWorld =
            new AnalyzedWorld(advisorsSupplier, shimTypes, mixinTypes, null);
    TransactionRegistry transactionRegistry = mock(TransactionRegistry.class);
    when(transactionRegistry.getCurrentThreadContextHolder())
            .thenReturn(new ThreadContextThreadLocal().getHolder());
    Weaver weaver = new Weaver(advisorsSupplier, shimTypes, mixinTypes, analyzedWorld,
            transactionRegistry, Ticker.systemTicker(), new TimerNameCache(),
            mock(ConfigService.class));
    isolatedWeavingClassLoader.setWeaver(weaver);

    String className = toBeDefinedImplClass.type().getClassName();
    isolatedWeavingClassLoader.addManualClass(className, toBeDefinedImplClass.bytes());
    @SuppressWarnings("unchecked")
    Class<T> implClass = (Class<T>) Class.forName(className, false, isolatedWeavingClassLoader);
    return isolatedWeavingClassLoader.newInstance(implClass, bridgeClass);
}
 
Example 20
Source File: ProportionalZoneFailureDetector.java    From brooklyn-server with Apache License 2.0 2 votes vote down vote up
/**
 * @param minDatapoints         min number of attempts within the time period, to consider this measure reliable
 * @param timeToConsider        time for recent attempts (discard any attempts older than this)
 * @param maxProportionFailures proportion (between 0 and 1) where numFailures/dataPoints >= this number means failure
 */
public ProportionalZoneFailureDetector(int minDatapoints, Duration timeToConsider, double maxProportionFailures) {
    this(minDatapoints, timeToConsider, maxProportionFailures, Ticker.systemTicker());
}