List of usage examples for java.util.concurrent.atomic AtomicInteger AtomicInteger
public AtomicInteger()
From source file:com.walmart.gatling.commons.ReportExecutor.java
private void runJob(Master.GenerateReport job) { TaskEvent taskEvent = job.reportJob.taskEvent; CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand()); Map<String, Object> map = new HashMap<>(); map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName()))); cmdLine.addArgument("${path}"); //parameters come from the task event for (Pair<String, String> pair : taskEvent.getParameters()) { cmdLine.addArgument(pair.getValue()); }/*from ww w . j a v a 2 s. c om*/ String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/"; cmdLine.addArgument(dir); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(agentConfig.getJob().getExitValues()); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setWorkingDirectory(new File(agentConfig.getJob().getPath())); FileOutputStream outFile = null; FileOutputStream errorFile = null; try { List<String> resultFiles = new ArrayList<>(job.results.size()); //download all files adn /*int i=0; for (Worker.Result result : job.results) { String destFile = dir + i++ + ".log"; resultFiles.add(destFile); DownloadFile.downloadFile(result.metrics,destFile); }*/ AtomicInteger index = new AtomicInteger(); job.results.parallelStream().forEach(result -> { String destFile = dir + index.incrementAndGet() + ".log"; resultFiles.add(destFile); DownloadFile.downloadFile(result.metrics, destFile); }); String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId); String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId); //create the std and err files outFile = FileUtils.openOutputStream(new File(outPath)); errorFile = FileUtils.openOutputStream(new File(errPath)); PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile), new ExecLogHandler(errorFile)); executor.setStreamHandler(psh); System.out.println(cmdLine); int exitResult = executor.execute(cmdLine); ReportResult result; if (executor.isFailure(exitResult)) { result = new ReportResult(dir, job.reportJob, false); log.info("Report Executor Failed, result: " + job.toString()); } else { result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true); log.info("Report Executor Completed, result: " + result.toString()); } for (String resultFile : resultFiles) { FileUtils.deleteQuietly(new File(resultFile)); } getSender().tell(result, getSelf()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(outFile); IOUtils.closeQuietly(errorFile); } }
From source file:com.github.rinde.logistics.pdptw.mas.comm.AuctionCommModel.java
AuctionCommModel(AuctionStopCondition<T> sc, Clock c, long maxAuctDurMs, @Nullable RandomGenerator r) { stopCondition = sc;/* w w w. j a v a 2 s. c o m*/ parcelAuctioneerMap = new LinkedHashMap<>(); maxAuctionDurationMs = maxAuctDurMs; rng = r == null ? null : new RandomAdaptor(r); eventDispatcher = new EventDispatcher(EventType.values()); if (c instanceof RealtimeClockController) { clock = (RealtimeClockController) c; } else { clock = null; } numAuctions = new AtomicInteger(); }
From source file:com.microsoft.wake.contrib.grouper.impl.CombiningSnowshovelGrouper.java
@Inject public CombiningSnowshovelGrouper(Combiner<OutType, K, V> c, Partitioner<K> p, Extractor<InType, K, V> ext, @Parameter(StageConfiguration.StageObserver.class) Observer<Tuple<Integer, OutType>> o, @Parameter(StageConfiguration.NumberOfThreads.class) int outputThreads, @Parameter(StageConfiguration.StageName.class) String stageName, @Parameter(ContinuousStage.PeriodNS.class) long outputPeriod_ns) { super(stageName); this.c = c;/* w w w . ja v a 2s . c o m*/ this.p = p; this.ext = ext; this.o = o; this.outputHandler = new OutputImpl(); // calling this.new on a @Unit's inner class without its own state is currently the same as Tang injecting it this.outputDriver = new ContinuousStage<Object>(outputHandler, outputThreads, stageName + "-output", outputPeriod_ns); this.doneHandler = ((ContinuousStage<Object>) outputDriver).getDoneHandler(); register = new ConcurrentSkipListMap<>(); inputDone = false; this.inputObserver = this.new InputImpl(); this.sleeping = new AtomicInteger(); // there is no dependence from input finish to output start // The alternative placement of this event is in the first call to onNext, // but Output onNext already provides blocking outputDriver.onNext(new GrouperEvent()); startTime = prevAdjustedTime = System.nanoTime(); prevCombinedCount = 0; combiningMeter = new Meter(stageName); }
From source file:com.cloudera.oryx.app.als.FeatureVectorsTest.java
@Test public void testConcurrent() throws Exception { FeatureVectors fv = new FeatureVectors(); AtomicInteger counter = new AtomicInteger(); int numWorkers = 16; int numIterations = 10000; ExecUtils.doInParallel(numWorkers, i -> { for (int j = 0; j < numIterations; j++) { int c = counter.getAndIncrement(); fv.setVector(Integer.toString(c), new float[] { c }); }/*w ww . ja va2 s. c om*/ }); assertEquals((long) numIterations * numWorkers, fv.size()); assertEquals((long) numIterations * numWorkers, counter.get()); ExecUtils.doInParallel(numWorkers, i -> { for (int j = 0; j < numIterations; j++) { fv.removeVector(Integer.toString(counter.decrementAndGet())); } }); assertEquals(0, fv.size()); }
From source file:de.blizzy.rust.lootconfig.LootConfigDump.java
private void run() throws IOException { LootConfig config = loadConfig(configFile); Table<LootContainer, Category, Multiset<Float>> dropChances = HashBasedTable.create(); Collection<LootContainer> lootContainers = config.LootContainers.values(); config.Categories.values().stream().filter(Category::hasItemsOrBlueprints).forEach(category -> { lootContainers.forEach(lootContainer -> { Multiset<Float> categoryInContainerDropChances = getItemCategoryDropChances(category, lootContainer);//from ww w.j av a 2 s .com if (!categoryInContainerDropChances.isEmpty()) { dropChances.put(lootContainer, category, categoryInContainerDropChances); } }); }); dropChances.rowKeySet().stream() .filter(lootContainer -> SHOW_DMLOOT || !lootContainer.name.contains("dmloot")) .sorted((lootContainer1, lootContainer2) -> Collator.getInstance().compare(lootContainer1.name, lootContainer2.name)) .forEach(lootContainer -> { System.out.printf("%s (blueprint fragments: %s)", lootContainer, lootContainer.DistributeFragments ? "yes" : "no").println(); Map<Category, Multiset<Float>> lootContainerDropChances = dropChances.row(lootContainer); AtomicDouble lootContainerDropChancesSum = new AtomicDouble(); AtomicInteger categoriesCount = new AtomicInteger(); lootContainerDropChances.entrySet().stream().sorted(this::compareByChances).limit(7) .forEach(categoryDropChancesEntry -> { Category category = categoryDropChancesEntry.getKey(); Multiset<Float> categoryDropChances = categoryDropChancesEntry.getValue(); float categoryDropChancesSum = sum(categoryDropChances); lootContainerDropChancesSum.addAndGet(categoryDropChancesSum); System.out.printf(" %s %s%s%s", formatPercent(categoryDropChancesSum), category, (category.Items.size() > 0) ? " (" + formatItems(category) + ")" : "", (category.Blueprints.size() > 0) ? " [" + formatBlueprints(category) + "]" : "") .println(); categoriesCount.incrementAndGet(); }); if (categoriesCount.get() < lootContainerDropChances.size()) { System.out.printf(" %s other (%d)", formatPercent(1f - (float) lootContainerDropChancesSum.get()), lootContainerDropChances.size() - categoriesCount.get()).println(); } }); }
From source file:org.jboss.aerogear.test.api.extension.SenderStatisticsRequest.java
public void await(final int expectedTokenCount, Duration timeout) { final AtomicInteger found = new AtomicInteger(); try {// w w w . j av a2s . com Awaitility.await().atMost(timeout).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { SenderStatistics statistics = get(); found.set(statistics.deviceTokens != null ? statistics.deviceTokens.size() : 0); return found.get() == expectedTokenCount; } }); } catch (ConditionTimeoutException e) { System.err.println("SenderStats: Was expecting " + expectedTokenCount + " tokens but " + found.get() + " " + "were found."); } }
From source file:com.netflix.spinnaker.igor.gitlabci.GitlabCiBuildMonitor.java
@Override protected BuildPollingDelta generateDelta(PollContext ctx) { final String master = ctx.partitionName; log.info("Checking for new builds for {}", kv("master", master)); final AtomicInteger updatedBuilds = new AtomicInteger(); final GitlabCiService gitlabCiService = (GitlabCiService) buildMasters.getMap().get(master); long startTime = System.currentTimeMillis(); final List<Project> projects = gitlabCiService.getProjects(); log.info("Took {} ms to retrieve {} repositories (master: {})", System.currentTimeMillis() - startTime, projects.size(), kv("master", master)); List<BuildDelta> delta = new ArrayList<>(); projects.parallelStream().forEach(project -> { List<Pipeline> pipelines = filterOldPipelines( gitlabCiService.getPipelines(project, MAX_NUMBER_OF_PIPELINES)); for (Pipeline pipeline : pipelines) { String branchedRepoSlug = GitlabCiPipelineUtis.getBranchedPipelineSlug(project, pipeline); boolean isPipelineRunning = GitlabCiResultConverter.running(pipeline.getStatus()); int cachedBuildId = buildCache.getLastBuild(master, branchedRepoSlug, isPipelineRunning); // In case of Gitlab CI the pipeline ids are increasing so we can use it for ordering if (pipeline.getId() > cachedBuildId) { updatedBuilds.incrementAndGet(); delta.add(new BuildDelta(branchedRepoSlug, project, pipeline, isPipelineRunning)); }/*from w w w . ja va2 s . co m*/ } }); if (!delta.isEmpty()) { log.info("Found {} new builds (master: {})", updatedBuilds.get(), kv("master", master)); } return new BuildPollingDelta(delta, master, startTime); }
From source file:de.uni_rostock.goodod.evaluator.OntologyTest.java
public OntologyTest(HierarchicalConfiguration testDescription) throws FileNotFoundException, IOException, OWLOntologyCreationException, ConfigurationException { // Get a reference to the global configuration: globalConfig = Configuration.getConfiguration(); threadCount = globalConfig.getInt("threadCount"); compCtor = getComparatorConstructor(globalConfig.getString("similarity")); testConfig = testDescription;/*from w w w . j a v a 2 s . c om*/ inProgressCount = new AtomicInteger(); // Gather URIs for the raw, model and student ontologies. String repoRoot = globalConfig.getString("repositoryRoot"); if (null == repoRoot) { repoRoot = ""; } String testDir = repoRoot + File.separator + globalConfig.getString("testDir"); String groupADir = ""; String groupBDir = ""; if (false == testConfig.getBoolean("notInRepository", false)) { groupADir = repoRoot + File.separator + globalConfig.configurationAt("groupDirs").getString("groupA") + File.separator; groupBDir = repoRoot + File.separator + globalConfig.configurationAt("groupDirs").getString("groupB") + File.separator; } File rawFile = null; if (testConfig.containsKey("rawOntology")) { rawFile = new File(testDir + File.separator + testConfig.getString("rawOntology")); rawOntology = rawFile.toURI(); } File modelFile = null; if (testConfig.containsKey("modelOntology")) { modelFile = new File(testDir + File.separator + testConfig.getString("modelOntology")); modelOntology = modelFile.toURI(); } groupAOntologies = new HashSet<URI>(12); groupBOntologies = new HashSet<URI>(12); failedComparisons = new HashMap<URI, Set<URI>>(); SubnodeConfiguration studentOntConf = testConfig.configurationAt("studentOntologies"); for (String fileName : studentOntConf.getStringArray("groupA")) { File studFile = new File(groupADir + fileName); groupAOntologies.add(studFile.toURI()); } for (String fileName : studentOntConf.getStringArray("groupB")) { File studFile = new File(groupBDir + fileName); groupBOntologies.add(studFile.toURI()); } // create the result map: resultMap = new HashMap<URI, Map<URI, ComparisonResult>>(25); // Get URIs for BioTopLite and the ignored imports. File biotopF = new File(globalConfig.getString("repositoryRoot") + File.separator + globalConfig.getString("bioTopLiteSource")); if (false == biotopF.canRead()) { logger.warn("Could not read BioTopLite."); } else { bioTopLiteURI = biotopF.toURI(); } testIRIs = getIRIsToTest(); considerImports = true; }
From source file:alfio.manager.support.CustomMessageManager.java
public void sendMessages(String eventName, Optional<Integer> categoryId, List<MessageModification> input, String username) {//w ww . j ava 2s .c o m Event event = eventManager.getSingleEvent(eventName, username); preview(event, input, username);//dry run for checking the syntax Organization organization = eventManager.loadOrganizer(event, username); AtomicInteger counter = new AtomicInteger(); Map<String, List<MessageModification>> byLanguage = input.stream() .collect(Collectors.groupingBy(m -> m.getLocale().getLanguage())); sendMessagesExecutor.execute(() -> { categoryId.map(id -> ticketRepository.findConfirmedByCategoryId(event.getId(), id)) .orElseGet(() -> ticketRepository.findAllConfirmed(event.getId())).stream() .filter(t -> isNotBlank(t.getFullName()) && isNotBlank(t.getEmail())).parallel().map(t -> { Model model = new ExtendedModelMap(); model.addAttribute("eventName", eventName); model.addAttribute("fullName", t.getFullName()); model.addAttribute("organizationName", organization.getName()); model.addAttribute("organizationEmail", organization.getEmail()); model.addAttribute("reservationURL", ticketReservationManager.reservationUrl(t.getTicketsReservationId(), event)); model.addAttribute("reservationID", ticketReservationManager.getShortReservationID(event, t.getTicketsReservationId())); model.addAttribute("ticketURL", ticketReservationManager.ticketUpdateUrl(event, t.getUuid())); return Triple.of(t, t.getEmail(), model); }).forEach(triple -> { Ticket ticket = triple.getLeft(); MessageModification m = Optional.ofNullable(byLanguage.get(ticket.getUserLanguage())) .orElseGet(() -> byLanguage.get(byLanguage.keySet().stream().findFirst() .orElseThrow(IllegalStateException::new))) .get(0); Model model = triple.getRight(); String subject = renderResource(m.getSubject(), model, m.getLocale(), templateManager); String text = renderResource(m.getText(), model, m.getLocale(), templateManager); List<Mailer.Attachment> attachments = new ArrayList<>(); if (m.isAttachTicket()) { ticketReservationManager.findById(ticket.getTicketsReservationId()) .ifPresent(reservation -> { ticketCategoryRepository.getByIdAndActive(ticket.getCategoryId()) .ifPresent(ticketCategory -> { attachments.add(generateTicketAttachment(ticket, reservation, ticketCategory, organization)); }); }); } counter.incrementAndGet(); notificationManager.sendSimpleEmail(event, triple.getMiddle(), subject, () -> text, attachments); }); }); }
From source file:org.atemsource.atem.utility.view.ViewBuilderTest.java
@Test public void testRemoveAndIncludePrimitives() { EntityType<EntityA> entityType = entityTypeRepository.getEntityType(EntityA.class); ViewBuilder viewBuilder = factory.create(entityType); viewBuilder.includePrimitives(false); viewBuilder.remove("intP"); View view = viewBuilder.create(); final Attribute intPAttribute = entityType.getAttribute("intP"); final AtomicInteger count = new AtomicInteger(); final ViewVisitor mockViewVisitor = new ViewVisitor<Object>() { @Override/* w w w. jav a 2 s.co m*/ public void visit(Object context, Attribute attribute) { if (attribute == intPAttribute) { Assert.fail("intP was removed"); } else if (attribute.getTargetType() instanceof PrimitiveType<?> && attribute instanceof SingleAttribute<?>) { count.incrementAndGet(); } else { Assert.fail("not a single primitive " + attribute.getCode()); } } @Override public void visit(Object context, Attribute attribute, Visitor<Object> visitor) { Assert.fail("not a primitive " + attribute.getCode()); } @Override public void visitSubView(Object context, View view, Visitor<Object> subViewVisitor) { } @Override public void visitSuperView(Object context, View view, Visitor<Object> superViewVisitor) { } }; HierachyVisitor.visit(view, mockViewVisitor, null); Assert.assertTrue(count.intValue() > 2); }