List of usage examples for java.util.concurrent.atomic AtomicInteger AtomicInteger
public AtomicInteger()
From source file:org.apache.asterix.experiment.client.SpatialQueryGenerator.java
public SpatialQueryGenerator(SpatialQueryGeneratorConfig config) { threadPool = Executors.newCachedThreadPool(new ThreadFactory() { private final AtomicInteger count = new AtomicInteger(); @Override//from w w w. j av a 2 s .c o m public Thread newThread(Runnable r) { int tid = count.getAndIncrement(); Thread t = new Thread(r, "DataGeneratorThread: " + tid); t.setDaemon(true); return t; } }); partitionRangeStart = config.getPartitionRangeStart(); duration = config.getDuration(); restHost = config.getRESTHost(); restPort = config.getRESTPort(); orchHost = config.getQueryOrchestratorHost(); orchPort = config.getQueryOrchestratorPort(); openStreetMapFilePath = config.getOpenStreetMapFilePath(); isIndexOnlyPlan = config.getIsIndexOnlyPlan(); }
From source file:com.neatresults.mgnltweaks.app.status.ConfigStatusPresenter.java
@Override public void refreshData() { List<String> fails = new ArrayList<String>(); final AtomicInteger totalCount = new AtomicInteger(); final AtomicInteger absCount = new AtomicInteger(); final AtomicInteger overrideCount = new AtomicInteger(); try {/*w w w .j a va 2s. c o m*/ Session session = MgnlContext.getJCRSession(RepositoryConstants.CONFIG); NodeIterator results = QueryUtil.search(RepositoryConstants.CONFIG, "select * from [nt:base] where extends is not null"); filterData(results, n -> { try { String path = n.getProperty("extends").getString(); if (StringUtils.startsWith(path, "/")) { absCount.incrementAndGet(); return session.itemExists(path); } else if ("override".equals(path)) { overrideCount.incrementAndGet(); return true; } else { return session.itemExists(n.getPath() + "/" + path); } } catch (RepositoryException e) { log.debug("Ooops, error while checking existence of extends target for {} with {}", n, e.getMessage(), e); return false; } }, t -> totalCount.incrementAndGet(), f -> { try { fails.add(f.getPath()); } catch (RepositoryException e) { log.debug("Ooops, error while reporting misconfigured extends target for {} with {}", f, e.getMessage(), e); } }); } catch (RepositoryException e) { log.debug("Ooops, error while searching for extends targets with {}", e.getMessage(), e); } sourceData(ConfigStatusView.EXTENDS_FAIL_COUNT, "" + fails.size()); sourceData(ConfigStatusView.EXTENDS_FAIL_LIST, fails); sourceData(ConfigStatusView.EXTENDS_COUNT, "" + totalCount.get()); sourceData(ConfigStatusView.ABS_EXTENDS_COUNT, "" + absCount.get()); sourceData(ConfigStatusView.REL_EXTENDS_COUNT, "" + (totalCount.get() - absCount.get() - overrideCount.get())); sourceData(ConfigStatusView.OVR_EXTENDS_COUNT, "" + overrideCount.get()); }
From source file:com.opinionlab.woa.WallOfAwesome.java
private static SockJSHandler makeEventStream(Vertx vertx) { final SockJSHandlerOptions options = new SockJSHandlerOptions().setHeartbeatInterval(2000); final SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options); sockJSHandler.socketHandler(socket -> { final AtomicInteger openCount = new AtomicInteger(); final AtomicBoolean running = new AtomicBoolean(true); LOGGER.info(format("[OPEN] Sockets: %d", openCount.incrementAndGet())); socket.endHandler(aVoid -> {/*from w w w . j ava 2 s . co m*/ running.set(false); LOGGER.info(format("[CLOSE] Sockets: %d", openCount.decrementAndGet())); }); socket.handler(buffer -> { String command = buffer.toString(); if ("purge".equals(command)) { EXECUTOR.execute(() -> { try { AwesomeImap.purge(s -> socket.write(buffer(objectToJson( HashTreePMap.empty().plus("deleted", true).plus("id", s.getId()), NO_TYPES)))); } catch (NoSuchProviderException e) { LOGGER.error("Could not purge messages", e); } }); } else { LOGGER.error(format("Unknown command: %s", command)); } }); try { final AtomicReference<Date> latestDate = new AtomicReference<>(new Date(0)); Consumer<Awesome> publishAwesome = awesome -> { socket.write(buffer(objectToJson(awesome, NO_TYPES))); final Date receivedDate = awesome.getReceivedDate(); if (latestDate.get().before(receivedDate)) { latestDate.set(receivedDate); } }; AwesomeImap.fetchAwesome().forEach(publishAwesome); EXECUTOR.execute(() -> { LOGGER.info("Polling started."); try { while (running.get()) { AwesomeImap.fetchAwesomeSince(latestDate.get()).forEach(publishAwesome); Thread.sleep(1000); } } catch (Throwable t) { running.set(false); socket.close(); LOGGER.error("Polling ended ABNORMALLY", t); } finally { LOGGER.info("Polling ended normally."); } }); } catch (MessagingException e) { LOGGER.error("Unable to fetch messages.", e); } }); return sockJSHandler; }
From source file:ch.windmobile.server.socialmodel.mogodb.HeavyLoadTest.java
public void testFullChatCycle() throws Exception { ServiceLocator locator = new MongoDBServiceLocator().connect(null); try {/* ww w . j a va 2 s .com*/ final int CNT = 50000; final Executor executor = Executors.newFixedThreadPool(10); final ChatService chatService = locator.getService(ChatService.class); final AtomicInteger counter = new AtomicInteger(); final CountDownLatch latch = new CountDownLatch(CNT); for (int i = 0; i < CNT; i++) { executor.execute(new Runnable() { @Override public void run() { chatService.postMessage("TestRoom", "aUser", "Hello, this is my message " + counter.incrementAndGet(), ""); latch.countDown(); } }); } System.out.println("Chat sent, waiting for the end..."); latch.await(2, TimeUnit.MINUTES); Messages ret = chatService.findMessages("TEST", 5); System.out.println("result : " + ret); } finally { locator.disconnect(); } }
From source file:edu.msu.cme.rdp.kmer.cli.KmerCoverage.java
/** * This program maps the kmers from reads to kmers on each contig, * writes the mean, median coverage of each contig to a file * writes the kmer abundance to a file/*from w ww . j a v a 2 s . c o m*/ * @param args * @throws IOException */ public static void main(String[] args) throws IOException, InterruptedException { int kmerSize = 45; final int maxThreads; final int maxTasks = 1000; final PrintStream match_reads_out; try { CommandLine cmdLine = new PosixParser().parse(options, args); args = cmdLine.getArgs(); if (args.length < 5) { throw new Exception("Unexpected number of arguments"); } kmerSize = Integer.parseInt(args[0]); if (kmerSize > Kmer.max_nucl_kmer_size) { throw new Exception("kmerSize should be less than " + Kmer.max_nucl_kmer_size); } if (cmdLine.hasOption("match_reads_out")) { match_reads_out = new PrintStream(cmdLine.getOptionValue("match_reads_out")); } else { match_reads_out = null; } if (cmdLine.hasOption("threads")) { maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads")); if (maxThreads >= Runtime.getRuntime().availableProcessors()) { System.err.println(" Runtime.getRuntime().availableProcessors() " + Runtime.getRuntime().availableProcessors()); } } else { maxThreads = 1; } final KmerCoverage kmerCoverage = new KmerCoverage(kmerSize, new SequenceReader(new File(args[1]))); final AtomicInteger outstandingTasks = new AtomicInteger(); ExecutorService service = Executors.newFixedThreadPool(maxThreads); Sequence seq; // parse one file at a time for (int index = 4; index < args.length; index++) { SequenceReader reader = new SequenceReader(new File(args[index])); while ((seq = reader.readNextSequence()) != null) { if (seq.getSeqString().length() < kmerSize) { continue; } final Sequence threadSeq = seq; Runnable r = new Runnable() { public void run() { try { kmerCoverage.processReads(threadSeq, match_reads_out); outstandingTasks.decrementAndGet(); } catch (Exception e) { e.printStackTrace(); } } }; outstandingTasks.incrementAndGet(); service.submit(r); while (outstandingTasks.get() >= maxTasks) ; } reader.close(); } service.shutdown(); service.awaitTermination(1, TimeUnit.DAYS); kmerCoverage.printCovereage(new FileOutputStream(new File(args[2])), new FileOutputStream(new File(args[3]))); if (match_reads_out != null) { match_reads_out.close(); } } catch (Exception e) { new HelpFormatter().printHelp( "KmerCoverage <kmerSize> <query_file> <coverage_out> <abundance_out> <reads_file> <reads_file>...\nmaximum kmerSize " + Kmer.max_nucl_kmer_size, options); e.printStackTrace(); System.exit(1); } }
From source file:com.astamuse.asta4d.web.util.timeout.DefaultSessionAwareTimeoutDataManager.java
@Override public void start() { // init fields dataMap = new ConcurrentHashMap<>(); dataCounter = new AtomicInteger(); service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override/*from w ww .java 2 s.co m*/ public Thread newThread(Runnable r) { return new Thread(r, checkThreadName); } }); // start check thread service.scheduleAtFixedRate(new Runnable() { @Override public void run() { List<Entry<String, DataHolder>> entries = new ArrayList<>(dataMap.entrySet()); long currentTime = System.currentTimeMillis(); int removedCounter = 0; Object existing; for (Entry<String, DataHolder> entry : entries) { if (entry.getValue().isExpired(currentTime)) { existing = dataMap.remove(entry.getKey()); if (existing != null) {// we removed it successfully removedCounter++; } } } if (removedCounter > 0) { dataCounter.addAndGet(-removedCounter); } } }, expirationCheckPeriodInMilliseconds, expirationCheckPeriodInMilliseconds, TimeUnit.MILLISECONDS); }
From source file:com.graphaware.reco.generic.stats.DefaultStatistics.java
/** * {@inheritDoc}/* ww w .j ava 2 s . c o m*/ */ @Override public void incrementStatistic(String task, String name) { ConcurrentMap<String, Object> taskStats = getStatistics(task); AtomicInteger count = (AtomicInteger) taskStats.get(name); if (count == null) { taskStats.putIfAbsent(name, new AtomicInteger()); count = (AtomicInteger) taskStats.get(name); } count.incrementAndGet(); }
From source file:com.fizzed.stork.deploy.Archive.java
public Path unpack(Path unpackDir) throws IOException { Files.createDirectories(unpackDir); log.info("Unpacking {} to {}", file, unpackDir); // we need to know the top-level dir(s) created by unpack final Set<Path> firstLevelPaths = new LinkedHashSet<>(); final AtomicInteger count = new AtomicInteger(); try (ArchiveInputStream ais = newArchiveInputStream(file)) { ArchiveEntry entry;// w ww . j av a 2s . c om while ((entry = ais.getNextEntry()) != null) { try { Path entryFile = Paths.get(entry.getName()); Path resolvedFile = unpackDir.resolve(entryFile); firstLevelPaths.add(entryFile.getName(0)); log.debug("{}", resolvedFile); if (entry.isDirectory()) { Files.createDirectories(resolvedFile); } else { unpackEntry(ais, resolvedFile); count.incrementAndGet(); } } catch (IOException | IllegalStateException | IllegalArgumentException e) { log.error("", e); throw new RuntimeException(e); } } } if (firstLevelPaths.size() != 1) { throw new IOException("Only archives with a single top-level directory are supported!"); } Path assemblyDir = unpackDir.resolve(firstLevelPaths.iterator().next()); log.info("Unpacked {} files to {}", count, assemblyDir); return assemblyDir; }
From source file:org.apache.solr.client.solrj.impl.CloudSolrClientCacheTest.java
public void testCaching() throws Exception { String collName = "gettingstarted"; Set<String> livenodes = new HashSet<>(); Map<String, ClusterState.CollectionRef> refs = new HashMap<>(); Map<String, DocCollection> colls = new HashMap<>(); class Ref extends ClusterState.CollectionRef { private String c; public Ref(String c) { super(null); this.c = c; }/*from w w w . ja va2 s . c om*/ @Override public boolean isLazilyLoaded() { return true; } @Override public DocCollection get() { gets.incrementAndGet(); return colls.get(c); } } Map<String, Function> responses = new HashMap<>(); NamedList okResponse = new NamedList(); okResponse.add("responseHeader", new NamedList<>(Collections.singletonMap("status", 0))); LBHttpSolrClient mockLbclient = getMockLbHttpSolrClient(responses); AtomicInteger lbhttpRequestCount = new AtomicInteger(); try (CloudSolrClient cloudClient = new CloudSolrClientBuilder(getStateProvider(livenodes, refs)) .withLBHttpSolrClient(mockLbclient).build()) { livenodes.addAll(ImmutableSet.of("192.168.1.108:7574_solr", "192.168.1.108:8983_solr")); ClusterState cs = ClusterState.load(1, coll1State.getBytes(UTF_8), Collections.emptySet(), "/collections/gettingstarted/state.json"); refs.put(collName, new Ref(collName)); colls.put(collName, cs.getCollectionOrNull(collName)); responses.put("request", o -> { int i = lbhttpRequestCount.incrementAndGet(); if (i == 1) return new ConnectException("TEST"); if (i == 2) return new SocketException("TEST"); if (i == 3) return new NoHttpResponseException("TEST"); return okResponse; }); UpdateRequest update = new UpdateRequest().add("id", "123", "desc", "Something 0"); cloudClient.request(update, collName); assertEquals(2, refs.get(collName).getCount()); } }
From source file:com.reactivetechnologies.blaze.throttle.DefaultConsumerThrottler.java
@PostConstruct public void init() { if (enabled) { addCommand(new ThrottleCommand()); List<? extends Command> customCommands = loadCommands(); if (customCommands != null) { for (Command cmd : customCommands) addCommand(cmd);// www .j a v a2 s .c om } counter = new AtomicInteger(); timer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable arg0) { Thread t = new Thread(arg0, "Throttler-timer-thread"); t.setDaemon(true); return t; } }); timer.scheduleWithFixedDelay(new MessageThrottlerTask(), 0, throttlerPeriod, TimeUnit.MILLISECONDS); log.info("Throttling enabled with period of " + throttlerPeriod + " millis"); } }