com.google.common.base.Ticker Java Examples

The following examples show how to use com.google.common.base.Ticker. 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: CappedDatabaseResizeTest.java    From glowroot with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: Weaver.java    From glowroot with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: TestDriftMethodInvocation.java    From drift with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #4
Source File: Backoff.java    From presto with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: TestDatasetVersion.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: DriftMethodInvocation.java    From drift with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
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 #8
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 #9
Source File: DriftMethodHandler.java    From drift with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #10
Source File: GuavaCacheRatelimiterTest.java    From Velocity with MIT License 6 votes vote down vote up
@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()));
}
 
Example #11
Source File: BookKeeper.java    From rubix with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #12
Source File: GaugeCollectorTest.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: AggregateDaoTest.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #14
Source File: ProportionalZoneFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #15
Source File: BKSyncLogReader.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
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;
            });
}
 
Example #16
Source File: CappedDatabaseOutputStream.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private CappedDatabaseOutputStream(File file, int requestedSizeKb, Ticker ticker)
        throws IOException {
    this.file = file;
    this.ticker = ticker;
    boolean newFile = !file.exists() || file.length() == 0;
    out = new RandomAccessFile(file, "rw");
    if (newFile) {
        currIndex = 0;
        sizeKb = requestedSizeKb;
        sizeBytes = sizeKb * 1024L;
        lastResizeBaseIndex = 0;
        out.writeLong(currIndex);
        out.writeInt(sizeKb);
        out.writeLong(lastResizeBaseIndex);
    } else {
        currIndex = out.readLong();
        // have to ignore requested fixedLength for existing files, must explicitly call
        // resize() since this can be an expensive operation
        sizeKb = out.readInt();
        sizeBytes = sizeKb * 1024L;
        lastResizeBaseIndex = out.readLong();
    }
    smallestNonOverwrittenId =
            calculateSmallestNonOverwrittenId(lastResizeBaseIndex, currIndex, sizeBytes);
    lastFsyncTick.set(ticker.read());
    fsyncScheduledRunnable = new FsyncRunnable();
}
 
Example #17
Source File: HttpVerificationService.java    From smartapp-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Build a verification service. This constructor is primarily for testing.
 */
HttpVerificationService(Duration keyCacheTTL, KeyResolver keyResolver, Ticker ticker) {
    publicKeysCache = CacheBuilder.newBuilder()
        .expireAfterWrite(keyCacheTTL)
        .ticker(ticker)
        .build(new CacheLoader<String, PublicKey>() {
            @Override
            public PublicKey load(String keyId) throws Exception {
                return parsePublicKey(keyResolver.getKeyString(keyId));
            }
        });
}
 
Example #18
Source File: DriftMethodInvocation.java    From drift with Apache License 2.0 5 votes vote down vote up
private DriftMethodInvocation(
        MethodInvoker invoker,
        MethodMetadata metadata,
        Map<String, String> headers,
        List<Object> parameters,
        RetryPolicy retryPolicy,
        AddressSelector<A> addressSelector,
        Optional<String> addressSelectionContext,
        MethodInvocationStat stat,
        Ticker ticker)
{
    this.invoker = requireNonNull(invoker, "methodHandler is null");
    this.metadata = requireNonNull(metadata, "metadata is null");
    this.headers = requireNonNull(headers, "headers is null");
    this.parameters = requireNonNull(parameters, "parameters is null");
    this.retryPolicy = requireNonNull(retryPolicy, "retryPolicy is null");
    this.addressSelector = requireNonNull(addressSelector, "addressSelector is null");
    this.addressSelectionContext = requireNonNull(addressSelectionContext, "addressSelectionContext is null");
    this.stat = requireNonNull(stat, "stat is null");
    this.ticker = requireNonNull(ticker, "ticker is null");
    this.startTime = ticker.read();

    // if this invocation is canceled, cancel the tasks
    super.addListener(() -> {
        if (super.isCancelled()) {
            onCancel(wasInterrupted());
        }
    }, directExecutor());
}
 
Example #19
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 #20
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 #21
Source File: GuavaCacheRatelimiter.java    From Velocity with MIT License 5 votes vote down vote up
@VisibleForTesting
GuavaCacheRatelimiter(long time, TimeUnit unit, Ticker ticker) {
  Preconditions.checkNotNull(unit, "unit");
  Preconditions.checkNotNull(ticker, "ticker");
  this.timeoutNanos = unit.toNanos(time);
  this.expiringCache = CacheBuilder.newBuilder()
      .ticker(ticker)
      .concurrencyLevel(Runtime.getRuntime().availableProcessors())
      .expireAfterWrite(time, unit)
      .build();
}
 
Example #22
Source File: DatabaseShardManager.java    From presto with Apache License 2.0 5 votes vote down vote up
@Inject
public DatabaseShardManager(
        @ForMetadata IDBI dbi,
        DaoSupplier<ShardDao> shardDaoSupplier,
        NodeSupplier nodeSupplier,
        AssignmentLimiter assignmentLimiter,
        Ticker ticker,
        MetadataConfig config)
{
    this(dbi, shardDaoSupplier, nodeSupplier, assignmentLimiter, ticker, config.getStartupGracePeriod());
}
 
Example #23
Source File: BookKeeper.java    From rubix with Apache License 2.0 5 votes vote down vote up
private static void initializeFileInfoCache(final Configuration conf, final Ticker ticker)
{
  ExecutorService executor = Executors.newSingleThreadExecutor();
  int expiryPeriod = CacheConfig.getStaleFileInfoExpiryPeriod(conf);
  fileInfoCache = CacheBuilder.newBuilder()
      .ticker(ticker)
      .expireAfterWrite(expiryPeriod, TimeUnit.SECONDS)
      .removalListener(new RemovalListener<String, FileInfo>()
      {
        @Override
        public void onRemoval(RemovalNotification<String, FileInfo> notification)
        {
          log.debug("Removed FileInfo for path " + notification.getKey() + " due to " + notification.getCause());
        }
      })
      .build(CacheLoader.asyncReloading(new CacheLoader<String, FileInfo>()
      {
        @Override
        public FileInfo load(String s) throws Exception
        {
          Path path = new Path(s);
          FileSystem fs = path.getFileSystem(conf);
          FileStatus status = fs.getFileStatus(path);
          FileInfo info = new FileInfo(status.getLen(), status.getModificationTime());
          return info;
        }
      }, executor));
}
 
Example #24
Source File: ThreadContextImplTest.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeEachTest() {
    Transaction transaction = mock(Transaction.class);
    MessageSupplier messageSupplier = mock(MessageSupplier.class);
    TimerNameImpl rootTimerName = mock(TimerNameImpl.class);
    Ticker ticker = mock(Ticker.class);
    ThreadContextThreadLocal.Holder threadContextHolder =
            mock(ThreadContextThreadLocal.Holder.class);
    threadContext =
            new ThreadContextImpl(transaction, null, null, messageSupplier, rootTimerName, 0,
                    false, 0, 0, null, false, ticker, threadContextHolder, null, 0, 0);
}
 
Example #25
Source File: AbstractGitHubApiTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Before
public void setUpFamework() throws Exception {
  MockitoAnnotations.initMocks(this);

  profiler = new Profiler(Ticker.systemTicker());
  profiler.init(ImmutableList.of(new LogProfilerListener()));
  api = new GitHubApi(getTransport(), profiler);
}
 
Example #26
Source File: SampledMovingAverageRate.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
SampledMovingAverageRate(int intervalSecs,
                         double scaleFactor,
                         Ticker ticker) {
    this.value = 0;
    this.total = new AtomicLong(0);
    this.scaleFactor = scaleFactor;
    this.ticker = ticker;
    this.samples = new LinkedBlockingDeque<>(intervalSecs);
}
 
Example #27
Source File: TraceDaoPerformanceMain.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DataSource dataSource = new DataSource();
    ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    CappedDatabase cappedDatabase = new CappedDatabase(new File("glowroot.capped.db"), 1000000,
            scheduledExecutor, Ticker.systemTicker());
    TraceDao traceDao = new TraceDao(dataSource, cappedDatabase,
            mock(TransactionTypeDao.class), mock(FullQueryTextDao.class),
            mock(TraceAttributeNameDao.class));

    Stopwatch stopwatch = Stopwatch.createStarted();
    for (int i = 0; i < 1000; i++) {
        traceDao.store(TraceTestData.createTraceReader());
    }
    logger.info("elapsed time: {}", stopwatch.elapsed(MILLISECONDS));
}
 
Example #28
Source File: CoordinatorBookKeeper.java    From rubix with Apache License 2.0 5 votes vote down vote up
/**
 * Create a cache for storing the status of worker node health checks.
 *
 * @param conf    The current Hadoop configuration.
 * @param ticker  The ticker used for determining expiry of cache entries.
 * @return a cache reflecting the health status of worker nodes.
 */
private Cache<String, Boolean> createHealthCache(Configuration conf, Ticker ticker)
{
  return CacheBuilder.newBuilder()
      .ticker(ticker)
      .expireAfterWrite(CacheConfig.getHealthStatusExpiry(conf), TimeUnit.MILLISECONDS)
      .build();
}
 
Example #29
Source File: PDFSProtocol.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new PDFS protocol instance.
 *
 * @param endpoint the local endpoint
 * @param config the Sabot configuration
 * @param allocator the memory allocator to use. The caller is in charge of closing it
 * @return the protocol
 * @throws IOException
 */
public static PDFSProtocol newInstance(NodeEndpoint endpoint, SabotConfig config, BufferAllocator allocator,
    boolean allowLocalHandling) throws IOException {
  // we'll grab a raw local file system so append is supported (rather than
  // the checksum local file system).
  Configuration conf = new Configuration();
  return new PDFSProtocol(endpoint, config, allocator,
      PseudoDistributedFileSystem.newLocalFileSystem(conf, allowLocalHandling), allowLocalHandling,
      Ticker.systemTicker());
}
 
Example #30
Source File: CoordinatorBookKeeper.java    From rubix with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public CoordinatorBookKeeper(Configuration conf, BookKeeperMetrics bookKeeperMetrics, Ticker ticker) throws FileNotFoundException
{
  super(conf, bookKeeperMetrics, ticker);
  this.isValidationEnabled = CacheConfig.isValidationEnabled(conf);
  this.liveWorkerCache = createHealthCache(conf, ticker);
  this.cachingValidatedWorkerCache = createHealthCache(conf, ticker);
  this.fileValidatedWorkerCache = createHealthCache(conf, ticker);

  registerMetrics();
}