微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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).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.",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,@SmileObjectMapper ObjectMapper objectMapper) {
    this(
            usageStatsClusterService,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.getpassword@R_400_4045@ion().setLastUpdateDate(new Date());

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

        for (String oldPassword : user.getpassword@R_400_4045@ion().getHistory()) {
            historyQueue.offer(oldPassword);
        }
        historyQueue.offer(user.getpasswordHash());

        user.getpassword@R_400_4045@ion().setHistory(Lists.newArrayList(historyQueue));
    }

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

    historyLogService.log(HistoryEventType.PASSWORD_UPDATE,user,HistoryLogAdditional@R_400_404[email protected]());
}
项目: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,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);
    }
}
项目: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,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,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 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,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,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,evictingQueue<UsageStatsRequest> evictingQueue,ObjectMapper objectMapper) {
    super(config,evictingQueue,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,"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 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,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,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 '{}': {}",e),e);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。