List of usage examples for java.util.concurrent.atomic AtomicInteger AtomicInteger
public AtomicInteger(int initialValue)
From source file:com.flipkart.bifrost.CommunicationTest.java
@Test public void testSendReceive() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); Connection connection = new Connection(Lists.newArrayList("localhost"), "guest", "guest"); connection.start();/* ww w .j a v a 2 s .c om*/ BifrostExecutor<Void> executor = BifrostExecutor.<Void>builder(TestAction.class).connection(connection) .objectMapper(mapper).requestQueue("bifrost-send").responseQueue("bifrost-recv").concurrency(10) .executorService(Executors.newFixedThreadPool(10)).build(); BifrostRemoteCallExecutionServer<Void> executionServer = BifrostRemoteCallExecutionServer .<Void>builder(TestAction.class).objectMapper(mapper).connection(connection).concurrency(10) .requestQueue("bifrost-send").build(); executionServer.start(); long startTime = System.currentTimeMillis(); AtomicInteger counter = new AtomicInteger(0); int requestCount = 100; CompletionService<Void> ecs = new ExecutorCompletionService<>(Executors.newFixedThreadPool(50)); List<Future<Void>> futures = Lists.newArrayListWithCapacity(requestCount); for (int i = 0; i < requestCount; i++) { futures.add(ecs.submit(new ServiceCaller(executor, counter))); } for (int i = 0; i < requestCount; i++) { try { ecs.take().get(); } catch (ExecutionException e) { e.printStackTrace(); } } System.out.println( String.format("Completed: %d in %d ms", counter.get(), (System.currentTimeMillis() - startTime))); executor.shutdown(); executionServer.stop(); connection.stop(); Assert.assertEquals(requestCount, counter.get()); }
From source file:net.myrrix.online.eval.AUCEvaluator.java
public EvaluationResult evaluate(final MyrrixRecommender recommender, final FastByIDMap<FastIDSet> testData) throws TasteException { final AtomicInteger underCurve = new AtomicInteger(0); final AtomicInteger total = new AtomicInteger(0); final long[] allItemIDs = recommender.getAllItemIDs().toArray(); Processor<Long> processor = new Processor<Long>() { private final RandomGenerator random = RandomManager.getRandom(); @Override/*from w w w. j ava 2s. com*/ public void process(Long userID, long count) throws ExecutionException { FastIDSet testItemIDs = testData.get(userID); int numTest = testItemIDs.size(); for (int i = 0; i < numTest; i++) { long randomTestItemID; long randomTrainingItemID; synchronized (random) { randomTestItemID = RandomUtils.randomFrom(testItemIDs, random); do { randomTrainingItemID = allItemIDs[random.nextInt(allItemIDs.length)]; } while (testItemIDs.contains(randomTrainingItemID)); } float relevantEstimate; float nonRelevantEstimate; try { relevantEstimate = recommender.estimatePreference(userID, randomTestItemID); nonRelevantEstimate = recommender.estimatePreference(userID, randomTrainingItemID); } catch (NoSuchItemException nsie) { // OK; it's possible item only showed up in test split continue; } catch (NoSuchUserException nsie) { // OK; it's possible user only showed up in test split continue; } catch (TasteException te) { throw new ExecutionException(te); } if (relevantEstimate > nonRelevantEstimate) { underCurve.incrementAndGet(); } total.incrementAndGet(); if (count % 100000 == 0) { log.info("AUC: {}", (double) underCurve.get() / total.get()); } } } }; try { new Paralleler<Long>(testData.keySetIterator(), processor, "AUCEval").runInParallel(); } catch (InterruptedException ie) { throw new TasteException(ie); } catch (ExecutionException e) { throw new TasteException(e.getCause()); } double score = (double) underCurve.get() / total.get(); log.info("AUC: {}", score); return new EvaluationResultImpl(score); }
From source file:org.dataconservancy.ui.it.support.CreateIdApiRequestIT.java
/** * Generates {@link #countToGenerate} ids, and insures that they are all unique. * * @throws Exception//from w w w. ja v a2 s .c o m */ @Test public void testGenerateUniqueIdsSingleThread() throws Exception { long start = Calendar.getInstance().getTimeInMillis(); for (int i = 0; i < countToGenerate; i++) { // Select an ID type to generate, based on a randomized seed. double seed = Math.random(); log.trace("Seed is {}", seed); Types t = selectType(seed, Types.values()); log.trace("Selected type {} with seed value {}", t, seed); // If debugging is enabled, keep track of the number of ids created for each type. if (log.isDebugEnabled()) { if (idTypeDistribution.containsKey(t)) { idTypeDistribution.get(t).getAndAdd(1); } else { idTypeDistribution.put(t, new AtomicInteger(1)); } } // Create an ID, and keep it in a Set. generatedIds.add(reqFactory.createIdApiRequest(t).execute(hc)); } if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("ID distribution:\n"); int totalGenerated = 0; for (Types t : Types.values()) { final Integer typeTotal = idTypeDistribution.get(t).get(); totalGenerated += typeTotal; sb.append("Type: ").append(t).append(" Count: ").append(typeTotal).append("\n"); } sb.append("Total generated: ").append(totalGenerated).append("\n"); sb.append("Unique generated: ").append(generatedIds.size()).append("\n"); sb.append("Execution time: ").append(Calendar.getInstance().getTimeInMillis() - start).append(" ms\n"); log.debug(sb.toString()); } // The number of generated IDs (stored in the Set) should equal 'countToGenerate' assertEquals("Expected " + countToGenerate + " to be generated, but the Set contained " + generatedIds.size() + ". Some ids may not have been unique.", countToGenerate, generatedIds.size()); }
From source file:com.graphaware.importer.stats.LoggingStatisticsCollector.java
private AtomicInteger getCounter(String category, String name) { if (name == null) { name = "null"; }//from w w w . j a v a 2s.co m ConcurrentHashMap<String, AtomicInteger> counter = counters.get(category); if (counter == null) { counters.putIfAbsent(category, new ConcurrentHashMap<String, AtomicInteger>()); counter = counters.get(category); } AtomicInteger count = counter.get(name); if (count == null) { counter.putIfAbsent(name, new AtomicInteger(0)); count = counter.get(name); } return count; }
From source file:com.ibasco.agql.core.RequestDetails.java
/** * Copy Constructor//from ww w.j a v a2 s.c o m * * @param requestDetails An {@link RequestDetails} that will be used as reference for the copy */ public RequestDetails(RequestDetails<Req, Res> requestDetails) { this.request = requestDetails.getRequest(); this.clientPromise = requestDetails.getClientPromise(); this.status = requestDetails.getStatus(); this.priority = requestDetails.getPriority(); this.retries = new AtomicInteger(requestDetails.getRetries()); this.expectedResponseClass = requestDetails.getExpectedResponseClass(); }
From source file:org.jtheque.undo.UndoServiceTest.java
@Test @DirtiesContext/* w w w . j ava 2s. com*/ public void listenerRemoved() { final AtomicInteger counter = new AtomicInteger(0); StateListener listener = new StateListener() { @Override public void stateChanged(String undoName, boolean canUndo, String redoName, boolean canRedo) { counter.incrementAndGet(); } }; undoService.addStateListener(listener); undoService.addEdit(new TestEdit(new AtomicInteger(0), new AtomicInteger(0))); undoService.removeStateListener(listener); undoService.addEdit(new TestEdit(new AtomicInteger(0), new AtomicInteger(0))); assertEquals(1, counter.intValue()); }
From source file:io.github.benas.jpopulator.impl.DefaultRandomizer.java
/** * Generate a random value for the given type. * * @param type the type for which a random value will be generated * @return a random value for the given type or null if the type is not supported *//*from w ww .j a v a2 s . co m*/ public static Object getRandomValue(final Class type) { /* * String and Character types */ if (type.equals(String.class)) { return RandomStringUtils.randomAlphabetic(ConstantsUtil.DEFAULT_STRING_LENGTH); } if (type.equals(Character.TYPE) || type.equals(Character.class)) { return RandomStringUtils.randomAlphabetic(1).charAt(0); } /* * Boolean type */ if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) { return ConstantsUtil.RANDOM.nextBoolean(); } /* * Numeric types */ if (type.equals(Byte.TYPE) || type.equals(Byte.class)) { return (byte) (ConstantsUtil.RANDOM.nextInt()); } if (type.equals(Short.TYPE) || type.equals(Short.class)) { return (short) (ConstantsUtil.RANDOM.nextInt()); } if (type.equals(Integer.TYPE) || type.equals(Integer.class)) { return ConstantsUtil.RANDOM.nextInt(); } if (type.equals(Long.TYPE) || type.equals(Long.class)) { return ConstantsUtil.RANDOM.nextLong(); } if (type.equals(Double.TYPE) || type.equals(Double.class)) { return ConstantsUtil.RANDOM.nextDouble(); } if (type.equals(Float.TYPE) || type.equals(Float.class)) { return ConstantsUtil.RANDOM.nextFloat(); } if (type.equals(BigInteger.class)) { return new BigInteger( Math.abs(ConstantsUtil.RANDOM.nextInt(ConstantsUtil.DEFAULT_BIG_INTEGER_NUM_BITS_LENGTH)), ConstantsUtil.RANDOM); } if (type.equals(BigDecimal.class)) { return new BigDecimal(ConstantsUtil.RANDOM.nextDouble()); } if (type.equals(AtomicLong.class)) { return new AtomicLong(ConstantsUtil.RANDOM.nextLong()); } if (type.equals(AtomicInteger.class)) { return new AtomicInteger(ConstantsUtil.RANDOM.nextInt()); } /* * Date and time types */ if (type.equals(java.util.Date.class)) { return ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue(); } if (type.equals(java.sql.Date.class)) { return new java.sql.Date(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(java.sql.Time.class)) { return new java.sql.Time(ConstantsUtil.RANDOM.nextLong()); } if (type.equals(java.sql.Timestamp.class)) { return new java.sql.Timestamp(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(Calendar.class)) { return Calendar.getInstance(); } if (type.equals(org.joda.time.DateTime.class)) { return new org.joda.time.DateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(org.joda.time.LocalDate.class)) { return new org.joda.time.LocalDate(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(org.joda.time.LocalTime.class)) { return new org.joda.time.LocalTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(org.joda.time.LocalDateTime.class)) { return new org.joda.time.LocalDateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime()); } if (type.equals(org.joda.time.Duration.class)) { return new org.joda.time.Duration(Math.abs(ConstantsUtil.RANDOM.nextLong())); } if (type.equals(org.joda.time.Period.class)) { return new org.joda.time.Period(Math.abs(ConstantsUtil.RANDOM.nextInt())); } if (type.equals(org.joda.time.Interval.class)) { long startDate = Math.abs(ConstantsUtil.RANDOM.nextInt()); long endDate = startDate + Math.abs(ConstantsUtil.RANDOM.nextInt()); return new org.joda.time.Interval(startDate, endDate); } /* * Enum type */ if (type.isEnum() && type.getEnumConstants().length > 0) { Object[] enumConstants = type.getEnumConstants(); return enumConstants[ConstantsUtil.RANDOM.nextInt(enumConstants.length)]; } /* * Return null for any unsupported type */ return null; }
From source file:de.qaware.chronix.importer.csv.FileImporter.java
/** * Reads the given file / folder and calls the bi consumer with the extracted points * * @param points/*from w w w. j a va 2 s . c om*/ * @param folder * @param databases * @return */ public Pair<Integer, Integer> importPoints(Map<Attributes, Pair<Instant, Instant>> points, File folder, BiConsumer<List<ImportPoint>, Attributes>... databases) { final AtomicInteger pointCounter = new AtomicInteger(0); final AtomicInteger tsCounter = new AtomicInteger(0); final File metricsFile = new File(METRICS_FILE_PATH); LOGGER.info("Writing imported metrics to {}", metricsFile); LOGGER.info("Import supports csv files as well as gz compressed csv files."); try { final FileWriter metricsFileWriter = new FileWriter(metricsFile); Collection<File> files = new ArrayList<>(); if (folder.isFile()) { files.add(folder); } else { files.addAll(FileUtils.listFiles(folder, new String[] { "gz", "csv" }, true)); } AtomicInteger counter = new AtomicInteger(0); files.parallelStream().forEach(file -> { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); NumberFormat nf = DecimalFormat.getInstance(numberLocal); InputStream inputStream = null; BufferedReader reader = null; try { inputStream = new FileInputStream(file); if (file.getName().endsWith("gz")) { inputStream = new GZIPInputStream(inputStream); } reader = new BufferedReader(new InputStreamReader(inputStream)); //Read the first line String headerLine = reader.readLine(); if (headerLine == null || headerLine.isEmpty()) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.debug("File is empty {}. File {} removed {}", file.getName(), deleted); return; } //Extract the attributes from the file name //E.g. first_second_third_attribute.csv String[] fileNameMetaData = file.getName().split("_"); String[] metrics = headerLine.split(csvDelimiter); Map<Integer, Attributes> attributesPerTimeSeries = new HashMap<>(metrics.length); for (int i = 1; i < metrics.length; i++) { String metric = metrics[i]; String metricOnlyAscii = Normalizer.normalize(metric, Normalizer.Form.NFD); metricOnlyAscii = metric.replaceAll("[^\\x00-\\x7F]", ""); Attributes attributes = new Attributes(metricOnlyAscii, fileNameMetaData); //Check if meta data is completely set if (isEmpty(attributes)) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.info("Attributes contains empty values {}. File {} deleted {}", attributes, file.getName(), deleted); continue; } if (attributes.getMetric().equals(".*")) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.info("Attributes metric{}. File {} deleted {}", attributes.getMetric(), file.getName(), deleted); continue; } attributesPerTimeSeries.put(i, attributes); tsCounter.incrementAndGet(); } Map<Integer, List<ImportPoint>> dataPoints = new HashMap<>(); String line; while ((line = reader.readLine()) != null) { String[] splits = line.split(csvDelimiter); String date = splits[0]; Instant dateObject; if (instantDate) { dateObject = Instant.parse(date); } else if (sdfDate) { dateObject = sdf.parse(date).toInstant(); } else { dateObject = Instant.ofEpochMilli(Long.valueOf(date)); } for (int column = 1; column < splits.length; column++) { String value = splits[column]; double numericValue = nf.parse(value).doubleValue(); ImportPoint point = new ImportPoint(dateObject, numericValue); if (!dataPoints.containsKey(column)) { dataPoints.put(column, new ArrayList<>()); } dataPoints.get(column).add(point); pointCounter.incrementAndGet(); } } dataPoints.values().forEach(Collections::sort); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(inputStream); dataPoints.forEach((key, importPoints) -> { for (BiConsumer<List<ImportPoint>, Attributes> database : databases) { database.accept(importPoints, attributesPerTimeSeries.get(key)); } points.put(attributesPerTimeSeries.get(key), Pair.of(importPoints.get(0).getDate(), importPoints.get(importPoints.size() - 1).getDate())); //write the stats to the file Instant start = importPoints.get(0).getDate(); Instant end = importPoints.get(importPoints.size() - 1).getDate(); try { writeStatsLine(metricsFileWriter, attributesPerTimeSeries.get(key), start, end); } catch (IOException e) { LOGGER.error("Could not write stats line", e); } LOGGER.info("{} of {} time series imported", counter.incrementAndGet(), tsCounter.get()); }); } catch (Exception e) { LOGGER.info("Exception while reading points.", e); } finally { //close all streams IOUtils.closeQuietly(reader); IOUtils.closeQuietly(inputStream); } }); } catch (Exception e) { LOGGER.error("Exception occurred during reading points."); } return Pair.of(tsCounter.get(), pointCounter.get()); }
From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java
public DefaultNetWorkClient(String hostName, int port) { this.hostName = hostName; this.port = port; state = new AtomicInteger(NetworkStateEnum.NETWORK_STATE_DISCONNECT.value); isWeakuped = new AtomicBoolean(false); inputBuffer = new LinkedBlockingQueue<ByteBuffer>(); outputBuffer = new LinkedBlockingQueue<Command>(); waitMoreDataLock = new byte[0]; }
From source file:com.adaptris.core.interceptor.InFlightWorkflowInterceptor.java
@Override public void start() throws CoreException { messagesInFlight = new AtomicInteger(0); }