List of usage examples for java.util.concurrent.atomic AtomicInteger getAndIncrement
public final int getAndIncrement()
From source file:org.niord.core.geojson.PlainTextConverter.java
/** Formats the coordinates of the geometry **/ private void formatCoordinates(StringBuilder result, GeoJsonVo g, Map<String, Object> properties) { Format format = PositionFormatter.LATLON_DEC; Locale locale = new Locale(languages.get(0)); AtomicInteger coordIndex = new AtomicInteger(0); g.visitCoordinates(xy -> {//from ww w . j av a 2s .co m result.append(PositionFormatter.format(locale, format, xy[1], xy[0])); formatFeatureName(result, "name:" + coordIndex.getAndIncrement() + ":", properties); }); }
From source file:com.cloudant.http.interceptors.Replay429Interceptor.java
@Override public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { // Get or init the stored context for this interceptor try {//www.j av a 2s. c om HttpURLConnection urlConnection = context.connection.getConnection(); int code = urlConnection.getResponseCode(); // We only want to take action on a 429 response if (code != 429) { return context; } // We received a 429 // Get the counter from the request context state AtomicInteger attemptCounter = context.getState(this, ATTEMPT, AtomicInteger.class); // If there was no counter yet, then this is the first 429 received for this request if (attemptCounter == null) { context.setState(this, ATTEMPT, (attemptCounter = new AtomicInteger())); } // Get the current value, and then increment for the next time round int attempt = attemptCounter.getAndIncrement(); // Check if we have remaining replays if (attempt < numberOfReplays && context.connection.getNumberOfRetriesRemaining() > 0) { // Calculate the backoff time, 2^n * initial sleep long sleepTime = initialSleep * Math.round(Math.pow(2, attempt)); // If the response includes a Retry-After then that is when we will retry, otherwise // we use the doubling sleep String retryAfter = preferRetryAfter ? urlConnection.getHeaderField("Retry-After") : null; if (retryAfter != null) { // See https://tools.ietf.org/html/rfc6585#section-4 // Whilst not specified for 429 for 3xx or 503 responses the Retry-After header // is expressed as an integer number of seconds or a date in one of the 3 HTTP // date formats https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 // Cloudant servers should give us an integer number of seconds, so don't worry // about parsing dates for now. try { sleepTime = Long.parseLong(retryAfter) * 1000; if (sleepTime > RETRY_AFTER_CAP) { sleepTime = RETRY_AFTER_CAP; logger.severe("Server specified Retry-After value in excess of one " + "hour, capping retry."); } } catch (NumberFormatException nfe) { logger.warning( "Invalid Retry-After value from server falling back to " + "default backoff."); } } // Read the reasons and log a warning InputStream errorStream = urlConnection.getErrorStream(); try { String errorString = IOUtils.toString(errorStream, "UTF-8"); logger.warning(errorString + " will retry in " + sleepTime + " ms"); } finally { errorStream.close(); } logger.fine("Too many requests backing off for " + sleepTime + " ms."); // Sleep the thread for the appropriate backoff time try { TimeUnit.MILLISECONDS.sleep(sleepTime); } catch (InterruptedException e) { logger.fine("Interrupted during 429 backoff wait."); // If the thread was interrupted we'll just continue and try again a bit earlier // than planned. } // Get ready to replay the request after the backoff time context.replayRequest = true; return context; } else { return context; } } catch (IOException e) { throw new HttpConnectionInterceptorException(e); } }
From source file:com.sillelien.dollar.api.types.DollarList.java
@NotNull @Override/*w w w. j a v a2 s . co m*/ public ImmutableMap<var, var> toVarMap() { AtomicInteger counter = new AtomicInteger(); return list.stream().map(var -> DollarStatic.$(String.valueOf(counter.getAndIncrement()), var)) .collect(Collectors.reducing(CollectionAware::$append)).get().toVarMap(); }
From source file:voldemort.store.bdb.BdbStorageEngineTest.java
@Test public void testSimultaneousIterationAndModification() throws Exception { // start a thread to do modifications ExecutorService executor = Executors.newFixedThreadPool(2); final Random rand = new Random(); final AtomicInteger count = new AtomicInteger(0); final AtomicBoolean keepRunning = new AtomicBoolean(true); executor.execute(new Runnable() { public void run() { while (keepRunning.get()) { byte[] bytes = Integer.toString(count.getAndIncrement()).getBytes(); store.put(new ByteArray(bytes), Versioned.value(bytes), null); count.incrementAndGet(); }//from ww w.jav a 2 s .c o m } }); executor.execute(new Runnable() { public void run() { while (keepRunning.get()) { byte[] bytes = Integer.toString(rand.nextInt(count.get())).getBytes(); store.delete(new ByteArray(bytes), new VectorClock()); count.incrementAndGet(); } } }); // wait a bit while (count.get() < 300) continue; // now simultaneously do iteration ClosableIterator<Pair<ByteArray, Versioned<byte[]>>> iter = this.store.entries(); while (iter.hasNext()) iter.next(); iter.close(); keepRunning.set(false); executor.shutdown(); assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); }
From source file:es.upm.oeg.tools.quality.ldsniffer.eval.Evaluation.java
private void incrementDerefCount(String uri, AtomicInteger derefCount) { HttpResponse response = responseMap.get(uri); if (response == null) { logger.error("Response is null - '{}'", uri); } else if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) { derefCount.getAndIncrement(); }//w w w . j a v a2 s. c o m }
From source file:org.sakaiproject.tool.assessment.facade.ItemHashUtil.java
private List<ItemDataIfc> itemsById(List<Long> itemIds, Map<String, String> hqlQueries, Session session) { if (itemIds == null || itemIds.isEmpty()) { return new ArrayList<>(0); }/*from w ww . j a v a2s . com*/ final String paramPlaceholders = StringUtils.repeat("?", ",", itemIds.size()); final Query query = session .createQuery(hqlQueries.get(ITEMS_BY_ID_HQL).replace(ID_PARAMS_PLACEHOLDER, paramPlaceholders)); final AtomicInteger position = new AtomicInteger(0); itemIds.forEach(id -> query.setParameter(position.getAndIncrement(), id)); return query.list(); }
From source file:musiccrawler.App.java
private void btnCrawlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCrawlActionPerformed if (Utils.isNull(rdgOptionCrawl.getSelection())) { JOptionPane.showMessageDialog(this, "Plz, check option before perform action crawl"); return;//from w w w . ja v a2 s . co m } String path = txtUrlInput.getText(); if (StringUtils.isEmpty(path)) { lblError.setText("Path is require"); lblError.setForeground(Color.RED); return; } boolean isGetAll = rdbGetAll.isSelected(); path = Validator.validPath(path); final DefaultTableModel defaultTableModel = new DefaultTableModel(isGetAll ? COLUMN_NAMES : COLUMN_STREAM, 0); AtomicInteger count = new AtomicInteger(); if (isGetAll) { List<Music> musics = musicCrawler.crawl(path); if (CollectionUtils.isNotEmpty(musics)) { musics.forEach(music -> { Object[] row = { count.getAndIncrement(), music.getId(), music.getTitle(), music.getImage(), music.getUrl(), music.getLyric(), music.getDescription(), music.getStream(), music.getQualityType().toString(), music.getSinger().getName(), music.getSinger().getAge(), music.getSinger().getDescription(), music.getSinger().getAvatar() }; defaultTableModel.addRow(row); }); } } else { Map<String, List<String>> results = musicCrawler.reCrawlLinkStream(path); List<String> musicIds = results.get("id"); List<String> listStream = results.get("stream"); musicIds.forEach(id -> { int index = count.getAndIncrement(); Object[] row = { index, id, listStream.get(index) }; defaultTableModel.addRow(row); }); } tbResultCrawlOnl.setModel(defaultTableModel); defaultTableModel.fireTableDataChanged(); tbResultCrawlOnl.setVisible(true); }
From source file:org.springframework.integration.mqtt.MqttAdapterTests.java
@Test public void testReconnect() throws Exception { final IMqttClient client = mock(IMqttClient.class); MqttPahoMessageDrivenChannelAdapter adapter = buildAdapter(client, null, ConsumerStopAction.UNSUBSCRIBE_NEVER); adapter.setRecoveryInterval(10);//from w w w .j a va 2 s . co m Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class)); new DirectFieldAccessor(adapter).setPropertyValue("logger", logger); given(logger.isDebugEnabled()).willReturn(true); final AtomicInteger attemptingReconnectCount = new AtomicInteger(); willAnswer(i -> { if (attemptingReconnectCount.getAndIncrement() == 0) { adapter.connectionLost(new RuntimeException("while schedule running")); } i.callRealMethod(); return null; }).given(logger).debug("Attempting reconnect"); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.initialize(); adapter.setTaskScheduler(taskScheduler); adapter.start(); adapter.connectionLost(new RuntimeException("initial")); Thread.sleep(1000); // the following assertion should be equalTo, but leq to protect against a slow CI server assertThat(attemptingReconnectCount.get(), lessThanOrEqualTo(2)); adapter.stop(); taskScheduler.destroy(); }
From source file:nl.knaw.huygens.alexandria.exporter.LaTeXExporterInMemory.java
private Map<Markup, Integer> calculateLayerIndex(List<Markup> markupList, Map<TextNode, Integer> textNodeIndex) { List<MarkupLayer> layers = new ArrayList<>(); markupList.forEach(tr -> {/*from w ww .j a v a2 s . c o m*/ Optional<MarkupLayer> oLayer = layers.stream().filter(layer -> layer.canAdd(tr)).findFirst(); if (oLayer.isPresent()) { oLayer.get().addMarkup(tr); } else { MarkupLayer layer = new MarkupLayer(textNodeIndex); layer.addMarkup(tr); layers.add(layer); } }); AtomicInteger layerCounter = new AtomicInteger(); Map<Markup, Integer> index = new HashMap<>(); layers.stream().sorted(ON_MAX_RANGE_SIZE).forEach(layer -> { int i = layerCounter.getAndIncrement(); layer.getMarkups().forEach(tr -> index.put(tr, i)); }); return index; }
From source file:com.basho.riak.pbc.itest.ITestDataLoad.java
@Test public void concurrentDataLoad() throws Exception { final int NUM_THREADS = 5; final int NUM_OBJECTS = 200; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(NUM_THREADS); final Thread[] threads = new Thread[NUM_THREADS]; final AtomicInteger idx = new AtomicInteger(0); final RiakClient riak = new RiakClient(RIAK_HOST, RIAK_PORT); for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(new Runnable() { public void run() { try { startLatch.await();//from ww w. j a v a 2 s. co m Random rnd = new Random(); for (int i = 0; i < NUM_OBJECTS / NUM_THREADS; i++) { String key = "data-load-" + idx.getAndIncrement(); String value = CharsetUtils.asString(data[rnd.nextInt(NUM_VALUES)], CharsetUtils.ISO_8859_1); RiakObject[] objects = riak.fetch(BUCKET, key); RiakObject o = null; if (objects.length == 0) { o = new RiakObject(BUCKET, key, value); } else { o = new RiakObject(objects[0].getVclock(), objects[0].getBucketBS(), objects[0].getKeyBS(), copyFromUtf8(value)); } RiakObject result = riak.store(o, new RequestMeta().w(2).returnBody(true))[0]; assertEquals(o.getBucket(), result.getBucket()); assertEquals(o.getKey(), result.getKey()); assertEquals(o.getValue(), result.getValue()); } endLatch.countDown(); } catch (Exception e) { throw new RuntimeException(e); } } }); threads[i].start(); } startLatch.countDown(); endLatch.await(); }