Java 类com.google.common.collect.EvictingQueue 实例源码

项目:ThriftJ    文件:FailoverStrategy.java   
public void fail(T object) {
    logger.info("Server {}:{} failed.", ((ThriftServer)object).getHost(),((ThriftServer)object).getPort());
    boolean addToFail = false;
    try {
        EvictingQueue<Long> evictingQueue = failCountMap.get(object);
        synchronized (evictingQueue) {
            evictingQueue.add(System.currentTimeMillis());
            if (evictingQueue.remainingCapacity() == 0 && evictingQueue.element() >= (System.currentTimeMillis() - failDuration)) {
                addToFail = true;
            }
        }
    } catch (ExecutionException e) {
        logger.error("Ops.", e);
    }
    if (addToFail) {
        failedList.put(object, Boolean.TRUE);
        logger.info("Server {}:{} failed. Add to fail list.", ((ThriftServer)object).getHost(), ((ThriftServer)object).getPort());
    }
}
项目:q-thrift    文件:FailoverCheckingStrategy.java   
/**
 * <p>
 * fail.
 * </p>
 *
 * @param object a T object.
 */
public void fail(T object) {
    logger.trace("server {} failed.", object);
    boolean addToFail = false;
    try {
        EvictingQueue<Long> evictingQueue = failCountMap.get(object);
        synchronized (evictingQueue) {
            evictingQueue.add(System.currentTimeMillis());
            if (evictingQueue.remainingCapacity() == 0
                    && evictingQueue.element() >= System.currentTimeMillis() - failDuration) {
                addToFail = true;
            }
        }
    } catch (ExecutionException e) {
        logger.error("Ops.", e);
    }
    if (addToFail) {
        failedList.put(object, TRUE);
        logger.trace("server {} failed. add to fail list.", object);
    }
}
项目:TokenJar    文件:PersistSettings.java   
private EvictingQueue<String> restore(EvictingQueue<String> queue, String queueName){
    String storedStr= callbacks.loadExtensionSetting(queueName);        
    if (storedStr == null)  return queue;

    EvictingQueue<String> newQueue=null;
    try (
        ByteArrayInputStream byteArrIn = new ByteArrayInputStream(storedStr.getBytes());
        ObjectInputStream objectIn = new ObjectInputStream(byteArrIn);
    ){  
        newQueue = (EvictingQueue<String>) objectIn.readObject();            
    } 
    catch (IOException | ClassNotFoundException ex) {
        PrintWriter stderr = new PrintWriter(callbacks.getStderr());
        ex.printStackTrace(stderr);
    }
    finally{
        if (newQueue==null) return queue; 
        else return newQueue;
    }     
}
项目:dropwizard-wiretap    文件:WiretapAppender.java   
@Override
public void start() {
    if (this.encoder == null) {
        addError("No encoder set for the appender named ["+ name +"].");
        return;
    }

    try {
        encoder.init(stream);
    } catch (IOException ignored) {
    }

    EvictingQueue<String> q = EvictingQueue.create(limit);
    logList = Queues.synchronizedQueue(q);

    isLoggingOn = true;

    super.start();
}
项目:opencensus-java    文件:SampledSpanStoreImpl.java   
private static void getSamplesFilteredByLatency(
    long latencyLowerNs,
    long latencyUpperNs,
    int maxSpansToReturn,
    List<SpanImpl> output,
    EvictingQueue<SpanImpl> queue) {
  for (SpanImpl span : queue) {
    if (output.size() >= maxSpansToReturn) {
      break;
    }
    long spanLatencyNs = span.getLatencyNs();
    if (spanLatencyNs >= latencyLowerNs && spanLatencyNs < latencyUpperNs) {
      output.add(span);
    }
  }
}
项目:java-timeseries    文件:ArimaProcess.java   
private ArimaProcess(Builder builder) {
    this.coefficients = builder.coefficients;
    this.distribution = builder.distribution;
    this.period = builder.period;
    this.seasonalCycle = builder.seasonalCycle;
    this.startTime = builder.startTime;
    this.currentTime = startTime;
    int seasonalFrequency = (int) builder.period.frequencyPer(builder.seasonalCycle);
    double[] arSarCoeffs = ArimaCoefficients.expandArCoefficients(coefficients.arCoeffs(),
                                                                  coefficients.seasonalARCoeffs(),

                                                                  seasonalFrequency);
    double[] maSmaCoeffs = ArimaCoefficients.expandMaCoefficients(coefficients.maCoeffs(),
                                                                  coefficients.seasonalMACoeffs(),
                                                                  seasonalFrequency);
    this.errors = EvictingQueue.create(maSmaCoeffs.length);
    this.diffSeries = EvictingQueue.create(arSarCoeffs.length);
    this.series = EvictingQueue.create(coefficients.d() + coefficients.D() * seasonalFrequency);
    this.maPoly = LagPolynomial.movingAverage(maSmaCoeffs);
    this.arPoly = LagPolynomial.autoRegressive(arSarCoeffs);
    this.diffPoly = LagPolynomial.differences(coefficients.d())
                                 .times(LagPolynomial.seasonalDifferences(seasonalFrequency, coefficients.D()));
}
项目:RadicalRobotics2017    文件:ExtensibleOpMode.java   
/**
 * Bootstraps the Extensible OpMode to the Xtensible library
 */
public ExtensibleOpMode() {
    super();

    loopCount = 0;
    skipNextLoop = 0;

    loopManager = new ExtensibleLoopManager();
    loopTimes = EvictingQueue.create(50);

    Log.i(TAG, "Starting OpMode: " + this.getClass().getSimpleName());
}
项目:graylog-plugin-anonymous-usage-statistics    文件:UsageStatsNodePeriodical.java   
@Inject
public UsageStatsNodePeriodical(UsageStatsNodeService usageStatsNodeService,
                                NodeId nodeId,
                                ServerStatus serverStatus,
                                UsageStatsConfiguration config,
                                ClusterConfigService clusterConfigService,
                                @CompressingHttpClient OkHttpClient httpClient,
                                @SmileObjectMapper ObjectMapper objectMapper) {
    this(
            usageStatsNodeService,
            nodeId,
            serverStatus,
            config,
            clusterConfigService,
            EvictingQueue.<UsageStatsRequest>create(config.getMaxQueueSize()),
            httpClient,
            objectMapper);
}
项目:graylog-plugin-anonymous-usage-statistics    文件:UsageStatsClusterPeriodical.java   
@Inject
public UsageStatsClusterPeriodical(UsageStatsClusterService usageStatsClusterService,
                                   ServerStatus serverStatus,
                                   UsageStatsConfiguration config,
                                   ClusterConfigService clusterConfigService,
                                   @CompressingHttpClient OkHttpClient httpClient,
                                   @SmileObjectMapper ObjectMapper objectMapper) {
    this(
            usageStatsClusterService,
            serverStatus,
            config,
            clusterConfigService,
            EvictingQueue.<UsageStatsRequest>create(config.getMaxQueueSize()),
            httpClient,
            objectMapper);
}
项目:simple-failover-java    文件:RecoverableCheckFailover.java   
@Override
public void fail(T object) {
    if (!getAll().contains(object)) {
        logger.warn("invalid fail obj:{}, it's not in original list.", object);
        return;
    }
    logger.warn("server {} failed.", object);
    boolean addToFail = false;
    EvictingQueue<Long> evictingQueue = failCountMap.getUnchecked(object);
    synchronized (evictingQueue) {
        evictingQueue.add(currentTimeMillis());
        if (evictingQueue.remainingCapacity() == 0
                && evictingQueue.element() >= currentTimeMillis() - failDuration) {
            addToFail = true;
        }
    }
    if (addToFail) {
        failedList.add(object);
    }
    recoveryFuture.get();
}
项目:owsi-core-parent    文件:SecurityManagementServiceImpl.java   
@Override
public void updatePassword(User user, String password, User author) throws ServiceException, SecurityServiceException {
    if (user == null || !StringUtils.hasText(password)) {
        return;
    }

    userService.setPasswords(user, password);
    user.getPasswordInformation().setLastUpdateDate(new Date());

    if (getOptions(user).isPasswordHistoryEnabled()) {
        EvictingQueue<String> historyQueue = EvictingQueue.create(propertyService.get(PASSWORD_HISTORY_COUNT));

        for (String oldPassword : user.getPasswordInformation().getHistory()) {
            historyQueue.offer(oldPassword);
        }
        historyQueue.offer(user.getPasswordHash());

        user.getPasswordInformation().setHistory(Lists.newArrayList(historyQueue));
    }

    user.getPasswordRecoveryRequest().reset();
    userService.update(user);

    historyLogService.log(HistoryEventType.PASSWORD_UPDATE, user, HistoryLogAdditionalInformationBean.empty());
}
项目:FOXopen    文件:TrackUtils.java   
/**
 * Creates a TrackLogger which can be recorded against the current session id, for later retrieval from the dev toolbar.
 * @param pRequestContext
 * @return
 */
public static TrackLogger createDefaultTrackLogger(RequestContext pRequestContext) {
  TrackLogger lNewTrackLogger = createDefaultTrackLogger(pRequestContext.getFoxRequest());

  //Get or create the recent track list for the given origin ID, then record this new track in it
  if(FoxGlobals.getInstance().isDevelopment() || InternalAuthentication.instance().getSessionAuthLevel(pRequestContext.getFoxRequest()).intValue() >= InternalAuthLevel.INTERNAL_SUPPORT.intValue()) {
    FoxCache<String, Queue<String>> lFoxCache = CacheManager.getCache(BuiltInCacheDefinition.RECENT_TRACK_IDS_FOR_SESSION_ID);
    Queue<String> lRecentTrackQueue = lFoxCache.get(pRequestContext.getFoxRequest().getHttpRequest().getSession().getId());
    if(lRecentTrackQueue == null) {
      lRecentTrackQueue = EvictingQueue.create(MAX_RECENT_TRACKS);
      lFoxCache.put(pRequestContext.getFoxRequest().getHttpRequest().getSession().getId(), lRecentTrackQueue);
    }
    lRecentTrackQueue.add(lNewTrackLogger.getTrackId());
  }

  return lNewTrackLogger;
}
项目:TeamClutch2016    文件:ExtensibleTelemetry.java   
public ExtensibleTelemetry(int dataPointsToSend, @NotNull Telemetry telemetry) {
    checkArgument(dataPointsToSend < MAX_DATA_MAX);

    this.parent = telemetry;

    this.dataPointsToSend = dataPointsToSend;
    cache = CacheBuilder.newBuilder().
            concurrencyLevel(4).
            expireAfterAccess(250, TimeUnit.MILLISECONDS).
            maximumSize(dataPointsToSend).build();

    dataCache = EvictingQueue.create((int) (dataPointsToSend * .75));
    data = LinkedHashMultimap.create();
    log = new LinkedList<>();

    try {
        logcat = Runtime.getRuntime().exec(new String[] {"logcat", "*:I"});
        reader = new BufferedReader(new InputStreamReader(logcat.getInputStream()));
    } catch (IOException e) {
        Log.e(TAG, "Cannot start logcat monitor", e);
    }

    executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new SendDataRunnable(), 250, 250, TimeUnit.MILLISECONDS);
}
项目:TeamClutch2016    文件:ExtensibleOpMode.java   
/**
     * Bootstraps the Extensible OpMode to the Xtensible library
     */
    protected ExtensibleOpMode() {
        this.gamepad1 = super.gamepad1;
        this.gamepad2 = super.gamepad2;
        this.hardwareMap = super.hardwareMap;

//        if (super.hardwareMap.appContext == null) {
//            RobotLog.w("App Context is null during construction.");
//        }

        this.telemetry = super.telemetry;
        loopCount = 0;
        skipNextLoop = 0;

        if (parent == null) {
            robotContext = new RobotContext(hardwareMap, telemetry);
            parent = this;
        } else {
            robotContext = parent.robotContext;
        }

        loopManager = new ExtensibleLoopManager();
        loopTimes = EvictingQueue.create(50);

        Log.i(TAG, "OpMode: " + this.getClass().getSimpleName());
    }
项目:POSEIDON    文件:SingleSpecieLogisticDelayGrowthBiology.java   
public SingleSpecieLogisticDelayGrowthBiology(
        Species species, double currentBiomass, double maxBiomass, int yearDelays, double aParameter,
        double bParameter) {
    Preconditions.checkArgument(yearDelays > 0, "Use undelayed biology rather than feeding 0 to a delayed one");
    Preconditions.checkArgument(maxBiomass > 0);
    Preconditions.checkArgument(currentBiomass <= maxBiomass);
    Preconditions.checkArgument(currentBiomass >= 0);
    this.species = species;
    this.yearDelays = yearDelays;
    pastBiomass = EvictingQueue.create(yearDelays);
    while(pastBiomass.remainingCapacity()>0)
        pastBiomass.add(currentBiomass);
    this.aParameter = aParameter;
    this.bParameter = bParameter;
    this.currentBiomass = currentBiomass;
    this.maxBiomass = maxBiomass;
}
项目:datacollector    文件:ProductionPipelineRunner.java   
private void retainErrorMessagesInMemory(Map<String, List<ErrorMessage>> errorMessages) {
  // Shortcut to avoid synchronization
  if(errorMessages.isEmpty()) {
    return;
  }

  synchronized (stageToErrorMessagesMap) {
    for (Map.Entry<String, List<ErrorMessage>> e : errorMessages.entrySet()) {
      EvictingQueue<ErrorMessage> errorMessageList = stageToErrorMessagesMap.get(e.getKey());
      if (errorMessageList == null) {
        errorMessageList = EvictingQueue.create(
          configuration.get(Constants.MAX_PIPELINE_ERRORS_KEY, Constants.MAX_PIPELINE_ERRORS_DEFAULT)
        );
        stageToErrorMessagesMap.put(e.getKey(), errorMessageList);
      }
      errorMessageList.addAll(errorMessages.get(e.getKey()));
    }
  }
}
项目:datacollector    文件:ProductionPipelineRunner.java   
private void retainErrorRecordsInMemory(Map<String, List<Record>> errorRecords) {
  // Shortcut to avoid synchronization
  if(errorRecords.isEmpty()) {
    return;
  }

  synchronized (stageToErrorRecordsMap) {
    for (Map.Entry<String, List<Record>> e : errorRecords.entrySet()) {
      EvictingQueue<Record> errorRecordList = stageToErrorRecordsMap.get(e.getKey());
      if (errorRecordList == null) {
        //replace with a data structure with an upper cap
        errorRecordList = EvictingQueue.create(
          configuration.get(Constants.MAX_ERROR_RECORDS_PER_STAGE_KEY, Constants.MAX_ERROR_RECORDS_PER_STAGE_DEFAULT)
        );
        stageToErrorRecordsMap.put(e.getKey(), errorRecordList);
      }
      errorRecordList.addAll(errorRecords.get(e.getKey()));
    }
  }
}
项目:datacollector    文件:SystemProcessImpl.java   
public Collection<String> getAllData() {
  EvictingQueue<String> result = EvictingQueue.create(2500);
  BufferedReader reader = null;
  try {
    reader = new BufferedReader(new FileReader(file));
    String line;
    while ((line = reader.readLine()) != null) {
      result.add(line);
    }
  } catch (IOException e) {
    String msg = Utils.format("Error reading from command output file '{}': {}", file, e);
    throw new RuntimeException(msg, e);
  } finally {
    if (reader != null) {
      try {
        reader.close();
      } catch (IOException ex) {
        // ignored
      }
    }
  }
  return result;
}
项目:GRIP    文件:AnalysisController.java   
@Subscribe
@SuppressWarnings("PMD.UnusedPrivateMethod")
private void onRun(TimerEvent event) {
  if (event.getTarget() instanceof Step) {
    Step source = (Step) event.getTarget();
    Optional<StepStatisticsEntry> possibleEntry
        = tableItems.stream().filter(e -> e.getStep() == source).findAny();
    Collection<Long> samples = sampleMap.computeIfAbsent(source,
        s -> EvictingQueue.create(numRecentSamples));
    samples.add(event.getElapsedTime());
    Statistics stepStatistics = Statistics.of(samples);
    if (possibleEntry.isPresent()) {
      possibleEntry.get().setStatistics(stepStatistics);
    } else {
      StepStatisticsEntry entry = new StepStatisticsEntry();
      entry.setStep(source);
      entry.setStatistics(stepStatistics);
      tableItems.add(entry);
    }
  }
}
项目:thrift-pool-client    文件:FailoverCheckingStrategy.java   
/**
 * <p>
 * fail.
 * </p>
 *
 * @param object a T object.
 */
public void fail(T object) {
    logger.trace("server {} failed.", object);
    boolean addToFail = false;
    try {
        EvictingQueue<Long> evictingQueue = failCountMap.get(object);
        synchronized (evictingQueue) {
            evictingQueue.add(System.currentTimeMillis());
            if (evictingQueue.remainingCapacity() == 0
                    && evictingQueue.element() >= System.currentTimeMillis() - failDuration) {
                addToFail = true;
            }
        }
    } catch (ExecutionException e) {
        logger.error("Ops.", e);
    }
    if (addToFail) {
        failedList.put(object, TRUE);
        logger.trace("server {} failed. add to fail list.", object);
    }
}
项目:geobit-chain    文件:Performance.java   
public void record(T t, Long millis) {
    Integer blackListRound=blacklist.get(t);
    if(millis==null) {
        Long error=ko.get(t);
        ko.put(t, error+1);
        blacklist.put(t, blackListRound + StaticNumbers.PENALTY_ROUND );
    } else {
        Long good=ok.get(t);
        ok.put(t, good+1);
        EvictingQueue<Long> times = timers.get(t);
        times.add(millis);
        int penalty=millis.intValue()/1000; /* every seconds 1 penalty round */
        if(penalty>0) {     
            blacklist.put(t, blackListRound + Math.min( penalty, StaticNumbers.PENALTY_ROUND ) );       
        }
    }
}
项目:geobit-chain    文件:Performance.java   
public String getElapsedOf(T prov) {
    EvictingQueue<Long> timer=timers.get(prov);

    if(timer!=null) {
        StringBuffer sb=new StringBuffer();
        int maxEl=10;
        for(Long l : timer) {
            if(maxEl--<=0)
                break;
            sb.append(l);
            sb.append(", ");
        }
        return sb.toString();
    }
    else
        return "";
}
项目:Elasticsearch    文件:SimulatedAnealingMinimizer.java   
/**
 * Runs the simulated annealing algorithm and produces a model with new coefficients that, theoretically
 * fit the data better and generalizes to future forecasts without overfitting.
 *
 * @param model         The MovAvgModel to be optimized for
 * @param train         A training set provided to the model, which predictions will be
 *                      generated from
 * @param test          A test set of data to compare the predictions against and derive
 *                      a cost for the model
 * @return              A new, minimized model that (theoretically) better fits the data
 */
public static MovAvgModel minimize(MovAvgModel model, EvictingQueue<Double> train, double[] test) {

    double temp = 1;
    double minTemp = 0.0001;
    int iterations = 100;
    double alpha = 0.9;

    MovAvgModel bestModel = model;
    MovAvgModel oldModel = model;

    double oldCost = cost(model, train, test);
    double bestCost = oldCost;

    while (temp > minTemp) {
        for (int i = 0; i < iterations; i++) {
            MovAvgModel newModel = oldModel.neighboringModel();
            double newCost = cost(newModel, train, test);

            double ap = acceptanceProbability(oldCost, newCost, temp);
            if (ap > Math.random()) {
                oldModel = newModel;
                oldCost = newCost;

                if (newCost < bestCost) {
                    bestCost = newCost;
                    bestModel = newModel;
                }
            }
        }

        temp *= alpha;
    }

    return bestModel;
}
项目:Elasticsearch    文件:SimulatedAnealingMinimizer.java   
/**
 * Calculates the "cost" of a model.  E.g. when run on the training data, how closely do the  predictions
 * match the test data
 *
 * Uses Least Absolute Differences to calculate error.  Note that this is not scale free, but seems
 * to work fairly well in practice
 *
 * @param model     The MovAvgModel we are fitting
 * @param train     A training set of data given to the model, which will then generate predictions from
 * @param test      A test set of data to compare against the predictions
 * @return          A cost, or error, of the model
 */
private static double cost(MovAvgModel model, EvictingQueue<Double> train, double[] test) {
    double error = 0;
    double[] predictions = model.predict(train, test.length);

    assert(predictions.length == test.length);

    for (int i = 0; i < predictions.length; i++) {
        error += Math.abs(test[i] - predictions[i]) ;
    }

    return error;
}
项目:joal    文件:Announcer.java   
public Announcer(final MockedTorrent torrent, final ConnectionHandler connectionHandler, final BitTorrentClient bitTorrentClient, final ApplicationEventPublisher publisher) {
    this.announceHistory = EvictingQueue.create(3);
    this.torrent = new TorrentWithStats(torrent);
    this.publisher = publisher;
    this.eventListeners = new ArrayList<>();
    this.trackerClientProvider = new TrackerClientProvider(this.torrent, connectionHandler, bitTorrentClient);
    this.moveToNextTrackerClient();

    this.thread = null;

    if (logger.isDebugEnabled()) {
        logger.debug("Initialized announce sub-system with {} trackers on {}.", new Object[]{this.torrent.getTorrent().getTrackerCount(), torrent});
    }
}
项目:ThriftJ    文件:FailoverStrategy.java   
/**
 * 自定义 failover 策略
 * @param failCount 失败次数
 * @param failDuration 失效持续时间
 * @param recoverDuration 恢复持续时间
 */
public FailoverStrategy(final int failCount, long failDuration, long recoverDuration) {
    this.failDuration = failDuration;
    this.failedList = CacheBuilder.newBuilder().weakKeys().expireAfterWrite(recoverDuration, TimeUnit.MILLISECONDS).build();
    this.failCountMap = CacheBuilder.newBuilder().weakKeys().build(new CacheLoader<T, EvictingQueue<Long>>() {
        @Override
        public EvictingQueue<Long> load(T key) throws Exception {
            return EvictingQueue.create(failCount);
        }
    });
}
项目:q-thrift    文件:FailoverCheckingStrategy.java   
/**
 * <p>
 * Constructor for FailoverCheckingStrategy.
 * </p>
 *
 * @param failDuration a long.
 * @param recoveryDuration a long.
 */
public FailoverCheckingStrategy(int failCount, long failDuration, long recoveryDuration) {
    this.failDuration = failDuration;
    this.failedList = newBuilder().weakKeys().expireAfterWrite(recoveryDuration, MILLISECONDS)
            .build();
    this.failCountMap = newBuilder().weakKeys().build(
            new CacheLoader<T, EvictingQueue<Long>>() {

                @Override
                public EvictingQueue<Long> load(T key) throws Exception {
                    return create(failCount);
                }
            });
}
项目:TokenJar    文件:PersistSettings.java   
private void save(EvictingQueue<String> queue, String queueName){
    try (
        ByteArrayOutputStream byteArrOut = new ByteArrayOutputStream();
        ObjectOutputStream objectOut = new ObjectOutputStream(byteArrOut);
    ){            
        objectOut.writeObject(queue);
        callbacks.saveExtensionSetting(queueName, byteArrOut.toString());
    } catch (IOException ex) {
        PrintWriter stderr = new PrintWriter(callbacks.getStderr());
        ex.printStackTrace(stderr);
    }
}
项目:metrics-aggregator-daemon    文件:VertxSink.java   
/**
 * Protected constructor.
 *
 * @param builder Instance of <code>Builder</code>.
 */
protected VertxSink(final Builder<?, ?> builder) {
    super(builder);
    _serverAddress = builder._serverAddress;
    _hostnameResolver = builder._hostnameResolver;
    _serverPort = builder._serverPort;
    _vertx = VertxFactory.newVertx();
    //Calling this just so the context gets created
    if (_vertx instanceof DefaultVertx) {
        final DefaultVertx vertx = (DefaultVertx) _vertx;
        final DefaultContext context = vertx.getOrCreateContext();
        vertx.setContext(context);
        _context = context;
    } else {
        _context = null;
        LOGGER.warn()
                .setMessage("Vertx instance not a DefaultVertx as expected. Threading may be incorrect.")
                .addData("sink", getName())
                .log();
    }

    _client = _vertx.createNetClient()
            .setReconnectAttempts(0)
            .setConnectTimeout(5000)
            .setTCPNoDelay(true)
            .setTCPKeepAlive(true);
    _socket = new AtomicReference<>();
    _pendingData = EvictingQueue.create(builder._maxQueueSize);
    _exponentialBackoffBase = builder._exponentialBackoffBase;

    connectToServer();
    consumeLoop();
}
项目:opencensus-java    文件:SampledSpanStoreImpl.java   
private static void getSamples(
    int maxSpansToReturn, List<SpanImpl> output, EvictingQueue<SpanImpl> queue) {
  for (SpanImpl span : queue) {
    if (output.size() >= maxSpansToReturn) {
      break;
    }
    output.add(span);
  }
}
项目:RadicalRobotics2017    文件:ExtensibleCameraManager.java   
/**
 * Creates a new Camera Manager
 *
 * @param ctx          Robot Context
 * @param captureDelay how many milliseconds should pass before we obtain a new preview
 */
public ExtensibleCameraManager(RobotContext ctx, int captureDelay) {
    context = ctx;
    imageQueue = EvictingQueue.create(5);
    latestTimestamp = new Date();

    previewCallback = new CameraPreviewCallback(ctx, captureDelay);
}
项目:LagMonitor    文件:PaperTimingsCommand.java   
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!isAllowed(sender, command)) {
        sender.sendMessage(org.bukkit.ChatColor.DARK_RED + "Not whitelisted");
        return true;
    }

    try {
        Class.forName(EXPORT_CLASS);
    } catch (ClassNotFoundException e) {
        sender.sendMessage(ChatColor.DARK_RED + "You aren't using PaperSpigot.");
        sender.sendMessage(ChatColor.DARK_RED + "This command is for the new timings (v2) system only");
        sender.sendMessage(ChatColor.DARK_RED + "Please use '/timing' for the old system");
        return true;
    }

    if (!Timings.isTimingsEnabled()) {
        sender.sendMessage(ChatColor.DARK_RED + "The server deactivated timing reports");
        sender.sendMessage(ChatColor.DARK_RED + "Go to paper.yml and activate timings");
        return true;
    }

    EvictingQueue<TimingHistory> history = Reflection.getField(TimingsManager.class, "HISTORY", EvictingQueue.class)
            .get(null);

    TimingHistory lastHistory = history.peek();
    if (lastHistory == null) {
        sender.sendMessage(ChatColor.DARK_RED + "Not enough data collected yet");
        return true;
    }

    List<BaseComponent[]> lines = Lists.newArrayList();
    printTimings(lines, lastHistory);

    Pagination pagination = new Pagination("Paper Timings", lines);
    pagination.send(sender);

    this.plugin.getPaginations().put(sender, pagination);
    return true;
}
项目:graylog-plugin-anonymous-usage-statistics    文件:UsageStatsPeriodical.java   
protected UsageStatsPeriodical(UsageStatsConfiguration config,
                               ClusterConfigService clusterConfigService,
                               EvictingQueue<UsageStatsRequest> usageStatsRequestsQueue,
                               OkHttpClient httpClient,
                               ObjectMapper objectMapper,
                               String filenamePattern) {
    this.config = checkNotNull(config);
    this.clusterConfigService = checkNotNull(clusterConfigService);
    this.cachedRequestsQueue = checkNotNull(usageStatsRequestsQueue);
    this.httpClient = checkNotNull(httpClient);
    this.objectMapper = checkNotNull(objectMapper);
    this.filenamePattern = checkNotNull(filenamePattern);
}
项目:graylog-plugin-anonymous-usage-statistics    文件:UsageStatsNodePeriodical.java   
private UsageStatsNodePeriodical(UsageStatsNodeService usageStatsNodeService,
                                 NodeId nodeId,
                                 ServerStatus serverStatus,
                                 UsageStatsConfiguration config,
                                 ClusterConfigService clusterConfigService,
                                 EvictingQueue<UsageStatsRequest> evictingQueue,
                                 OkHttpClient httpClient,
                                 ObjectMapper objectMapper) {
    super(config, clusterConfigService, evictingQueue, httpClient, objectMapper,
            "node-" + nodeId.anonymize() + "-%s.smile");
    this.serverStatus = serverStatus;
    this.nodeId = nodeId;
    this.usageStatsNodeService = usageStatsNodeService;
}
项目:graylog-plugin-anonymous-usage-statistics    文件:UsageStatsClusterPeriodical.java   
private UsageStatsClusterPeriodical(UsageStatsClusterService usageStatsClusterService,
                                    ServerStatus serverStatus,
                                    UsageStatsConfiguration config,
                                    ClusterConfigService clusterConfigService,
                                    EvictingQueue<UsageStatsRequest> evictingQueue,
                                    OkHttpClient httpClient,
                                    ObjectMapper objectMapper) {
    super(config, clusterConfigService, evictingQueue, httpClient, objectMapper, "cluster-%s.smile");
    this.serverStatus = serverStatus;
    this.usageStatsClusterService = usageStatsClusterService;
}
项目:viskell    文件:GhciSession.java   
/**
 * Builds a new communication session with ghci.
 *
 * Starting the backend is delayed until startAsync() is called.
 */
public GhciSession() {
    super();

    queue = new ArrayBlockingQueue<>(1024);
    errors = EvictingQueue.create(LOG_SIZE);
    switch (pickBackend()) {
        case Clash: 
            this.catalog = new HaskellCatalog("/catalog/clash.xml");
            break;
        default:
            this.catalog = new HaskellCatalog("/catalog/haskell.xml");
            break;
    }
}
项目:simple-failover-java    文件:RecoverableCheckFailover.java   
RecoverableCheckFailover(List<T> original, Predicate<T> checker, int failCount,
        long failDuration, long recoveryCheckDuration, boolean returnOriginalWhileAllFailed) {
    this.returnOriginalWhileAllFailed = returnOriginalWhileAllFailed;
    this.original = original;
    this.failDuration = failDuration;
    this.failCountMap = CacheBuilder.newBuilder().weakKeys()
            .build(new CacheLoader<T, EvictingQueue<Long>>() {

                @Override
                public EvictingQueue<Long> load(T key) throws Exception {
                    return create(failCount);
                }
            });
    recoveryFuture = lazy(() -> getInstance().scheduleWithFixedDelay(() -> {
        if (closed) {
            tryCloseScheduler();
            return;
        }
        if (failedList == null || failedList.isEmpty()) {
            return;
        }
        try {
            // 考虑到COWArraySet不支持iterator.remove,所以这里使用搜集->统一清理的策略
            List<T> covered = failedList.stream() //
                    .filter(checker) //
                    .peek(obj -> logger.info("obj:{} is recovered during test.", obj)) //
                    .collect(toList());
            failedList.removeAll(covered);
        } catch (Throwable e) {
            logger.error("Ops.", e);
        }
    }, recoveryCheckDuration, recoveryCheckDuration, MILLISECONDS));
}
项目:TeamClutch2016    文件:ExtensibleCameraManager.java   
/**
 * Creates a new Camera Manager
 *
 * @param ctx          Robot Context
 * @param captureDelay how many milliseconds should pass before we obtain a new preview
 */
public ExtensibleCameraManager(RobotContext ctx, int captureDelay) {
    context = ctx;
    imageQueue = EvictingQueue.create(5);
    latestTimestamp = new Date();

    previewCallback = new CameraPreviewCallback(ctx, captureDelay);
}
项目:che    文件:MessagesReSender.java   
public void resend(String endpointId) {
  Queue<DelayedMessage> delayedMessages = delayedMessageRegistry.remove(endpointId);

  if (delayedMessages == null || delayedMessages.isEmpty()) {
    return;
  }

  Optional<Session> sessionOptional = registry.get(endpointId);

  if (!sessionOptional.isPresent()) {
    return;
  }

  Queue<DelayedMessage> backingQueue = EvictingQueue.create(delayedMessages.size());
  while (!delayedMessages.isEmpty()) {
    backingQueue.offer(delayedMessages.poll());
  }

  Session session = sessionOptional.get();
  for (DelayedMessage delayedMessage : backingQueue) {
    if (session.isOpen()) {
      session.getAsyncRemote().sendText(delayedMessage.message);
    } else {
      delayedMessages.add(delayedMessage);
    }
  }

  if (!delayedMessages.isEmpty()) {
    delayedMessageRegistry.put(endpointId, delayedMessages);
  }
}
项目:datacollector    文件:SystemProcessImpl.java   
public SimpleFileTailer(File file) {
  this.file = file;
  this.history = EvictingQueue.create(2500);
  this.inbuf = new byte[8192 * 8];
  try {
    this.randomAccessFile = new RandomAccessFile(file, "r");
  } catch (FileNotFoundException e) {
    throw new RuntimeException(Utils.format("Unexpected error reading output file '{}': {}", file, e), e);
  }
}