List of usage examples for java.util.concurrent.atomic AtomicInteger getAndIncrement
public final int getAndIncrement()
From source file:org.apache.hadoop.hbase.client.TestAsyncSingleRequestRpcRetryingCaller.java
@Test public void testLocateError() throws IOException, InterruptedException, ExecutionException { AtomicBoolean errorTriggered = new AtomicBoolean(false); AtomicInteger count = new AtomicInteger(0); HRegionLocation loc = CONN.getRegionLocator(TABLE_NAME).getRegionLocation(ROW).get(); AsyncRegionLocator mockedLocator = new AsyncRegionLocator(CONN, AsyncConnectionImpl.RETRY_TIMER) { @Override//from w w w .j a va 2s .c om CompletableFuture<HRegionLocation> getRegionLocation(TableName tableName, byte[] row, RegionLocateType locateType, long timeoutNs) { if (tableName.equals(TABLE_NAME)) { CompletableFuture<HRegionLocation> future = new CompletableFuture<>(); if (count.getAndIncrement() == 0) { errorTriggered.set(true); future.completeExceptionally(new RuntimeException("Inject error!")); } else { future.complete(loc); } return future; } else { return super.getRegionLocation(tableName, row, locateType, timeoutNs); } } @Override void updateCachedLocation(HRegionLocation loc, Throwable exception) { } }; try (AsyncConnectionImpl mockedConn = new AsyncConnectionImpl(CONN.getConfiguration(), CONN.registry, CONN.registry.getClusterId().get(), User.getCurrent()) { @Override AsyncRegionLocator getLocator() { return mockedLocator; } }) { RawAsyncTable table = mockedConn.getRawTableBuilder(TABLE_NAME) .setRetryPause(100, TimeUnit.MILLISECONDS).setMaxRetries(5).build(); table.put(new Put(ROW).addColumn(FAMILY, QUALIFIER, VALUE)).get(); assertTrue(errorTriggered.get()); errorTriggered.set(false); count.set(0); Result result = table.get(new Get(ROW).addColumn(FAMILY, QUALIFIER)).get(); assertArrayEquals(VALUE, result.getValue(FAMILY, QUALIFIER)); assertTrue(errorTriggered.get()); } }
From source file:com.rapplogic.aru.uploader.wifi.WifiSketchUploader.java
@Override protected void open(final Map<String, Object> context) throws Exception { String host = (String) context.get("host"); Integer port = (Integer) context.get("port"); Integer connectionTimeoutSecs = (Integer) context.get("connectionTimeoutSecs"); Integer readTimeoutSecs = (Integer) context.get("readTimeoutSecs"); // open socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port), connectionTimeoutSecs * 1000); socket.setSoTimeout(readTimeoutSecs * 1000); connected = true;// w w w.java 2 s .c o m final int[] reply = new int[5]; final AtomicInteger replyIndex = new AtomicInteger(0); // TODO unlike other wireless protocols, wifi is stateful so we need to handle situations where we lose the socket and reconnect t = new Thread(new Runnable() { @Override public void run() { int ch = 0; // reply always terminated with 13,10 try { while ((ch = socket.getInputStream().read()) > -1) { if (replyIndex.get() < reply.length) { reply[replyIndex.getAndIncrement()] = ch; } else if (replyIndex.get() == 5 && ch == 13) { replyIndex.getAndIncrement(); // discard } else if (replyIndex.get() == 6 && ch == 10) { //System.out.println("reply is " + stringBuilder.toString()); // stringBuilder = new StringBuilder(); handleReply(reply); replyIndex.set(0); } else { //error throw new RuntimeException("Expected CR/LF -- invalid reply at position " + replyIndex.get() + ", array: " + intArrayToString(reply)); } } } catch (IOException e) { if (!connected && e instanceof SocketException) { // expected.. ignore } else { System.out.println("IO error in socket reader"); e.printStackTrace(); } } catch (Exception e) { System.out.println("Unexpected error in socket reader"); e.printStackTrace(); } connected = false; } }); t.setDaemon(true); t.start(); }
From source file:alfio.controller.api.admin.EventApiController.java
@RequestMapping(value = "/events/check", method = POST) public ValidationResult validateEvent(@RequestBody EventModification eventModification, Errors errors) { ValidationResult base = validateEventHeader(Optional.empty(), eventModification, errors) .or(validateEventPrices(Optional.empty(), eventModification, errors)) .or(eventModification.getAdditionalServices().stream() .map(as -> validateAdditionalService(as, eventModification, errors)) .reduce(ValidationResult::or).orElse(ValidationResult.success())); AtomicInteger counter = new AtomicInteger(); return base.or(eventModification.getTicketCategories().stream() .map(c -> validateCategory(c, errors, "ticketCategories[" + counter.getAndIncrement() + "].")) .reduce(ValidationResult::or).orElse(ValidationResult.success())) .or(validateAdditionalTicketFields(eventModification.getTicketFields(), errors)); }
From source file:alfio.controller.api.admin.EventApiController.java
private ValidationResult validateAdditionalTicketFields(List<EventModification.AdditionalField> ticketFields, Errors errors) {// w ww. ja v a2 s.co m //meh AtomicInteger cnt = new AtomicInteger(); return Optional.ofNullable(ticketFields).orElseGet(Collections::emptyList).stream().map(field -> { String prefix = "ticketFields[" + cnt.getAndIncrement() + "]"; if (StringUtils.isBlank(field.getName())) { errors.rejectValue(prefix + ".name", "error.required"); } //TODO: check label value is present for all the locales //TODO: for select check option value+label return Validator.evaluateValidationResult(errors); }).reduce(ValidationResult::or).orElseGet(ValidationResult::success); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerTests.java
@SuppressWarnings("unchecked") protected void setupMockConsume(Channel channel, final List<Consumer> consumers, final AtomicInteger consumerTag, final CountDownLatch latch) throws IOException { doAnswer(invocation -> {/*ww w . jav a 2s. c o m*/ Consumer cons = (Consumer) invocation.getArguments()[6]; consumers.add(cons); String actualTag = String.valueOf(consumerTag.getAndIncrement()); cons.handleConsumeOk(actualTag); latch.countDown(); return actualTag; }).when(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class)); }
From source file:org.apache.servicemix.jbi.cluster.engine.ClusterEndpointLoadTest.java
public void testLoadInOnly() throws Exception { createRoute(Transacted.Jms, true, false, true); final int nbThreads = 10; final int nbExchanges = 10; final ReadWriteLock lock = new ReentrantReadWriteLock(); final CountDownLatch latch = new CountDownLatch(nbThreads); final AtomicInteger id = new AtomicInteger(); lock.writeLock().lock();//from w w w . j a va 2s.c om for (int i = 0; i < nbThreads; i++) { new Thread() { public void run() { Channel client = null; try { client = nmr1.createChannel(); lock.readLock().lock(); for (int i = 0; i < nbExchanges; i++) { Exchange exchange = client.createExchange(Pattern.InOnly); exchange.getIn() .setBody(new StringSource("<hello id='" + id.getAndIncrement() + "'/>")); exchange.setTarget(nmr1.getEndpointRegistry() .lookup(ServiceHelper.createMap(Endpoint.NAME, PROXY_ENDPOINT_NAME))); client.sendSync(exchange); assertEquals(Status.Done, exchange.getStatus()); } } catch (Exception e) { e.printStackTrace(); } finally { lock.readLock().unlock(); latch.countDown(); if (client != null) { client.close(); } } } }.start(); } long t0, t1; t0 = System.currentTimeMillis(); lock.writeLock().unlock(); latch.await(); receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT); t1 = System.currentTimeMillis(); System.err.println("Elapsed time: " + (t1 - t0) + " ms"); System.err.println("Throuput: " + (nbThreads * nbExchanges * 1000 / (t1 - t0)) + " messages/sec"); }
From source file:org.apache.servicemix.jbi.cluster.engine.ReconnectTest.java
public void testLoadInOnly() throws Exception { createRoute(Transacted.Jms, true, false, false); final int nbThreads = 10; final int nbExchanges = 10; final ReadWriteLock lock = new ReentrantReadWriteLock(); final CountDownLatch latch = new CountDownLatch(nbThreads); final AtomicInteger id = new AtomicInteger(); lock.writeLock().lock();// ww w . ja v a 2 s .c om for (int i = 0; i < nbThreads; i++) { new Thread() { public void run() { Channel client = null; try { client = nmr1.createChannel(); lock.readLock().lock(); for (int i = 0; i < nbExchanges; i++) { Exchange exchange = client.createExchange(Pattern.InOnly); exchange.getIn() .setBody(new StringSource("<hello id='" + id.getAndIncrement() + "'/>")); exchange.setTarget(nmr1.getEndpointRegistry() .lookup(ServiceHelper.createMap(Endpoint.NAME, PROXY_ENDPOINT_NAME))); client.sendSync(exchange); assertEquals(Status.Done, exchange.getStatus()); } } catch (Exception e) { e.printStackTrace(); } finally { lock.readLock().unlock(); latch.countDown(); if (client != null) { client.close(); } } } }.start(); } long t0, t1; cluster2.pause(); t0 = System.currentTimeMillis(); lock.writeLock().unlock(); latch.await(); broker.stop(); cluster2.resume(); Thread.sleep(500); broker = createBroker(false); receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT); //Thread.sleep(500); //receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT); t1 = System.currentTimeMillis(); System.err.println("Elapsed time: " + (t1 - t0) + " ms"); System.err.println("Throuput: " + (nbThreads * nbExchanges * 1000 / (t1 - t0)) + " messages/sec"); }
From source file:org.commonjava.indy.promote.data.PromotionManagerTest.java
@Test @Ignore("volatile, owing to galley fs locks") public void promoteAllByPath_RaceToPromote_FirstLocksTargetStore() throws Exception { Random rand = new Random(); final HostedRepository[] sources = { new HostedRepository(MAVEN_PKG_KEY, "source1"), new HostedRepository(MAVEN_PKG_KEY, "source2") }; final String[] paths = { "/path/path1", "/path/path2", "/path3", "/path/path/4" }; Stream.of(sources).forEach((source) -> { try {/*from w w w. j a v a 2 s . c o m*/ storeManager.storeArtifactStore(source, new ChangeSummary(ChangeSummary.SYSTEM_USER, "test setup"), false, true, new EventMetadata()); Stream.of(paths).forEach((path) -> { byte[] buf = new byte[1024 * 1024 * 2]; rand.nextBytes(buf); try { contentManager.store(source, path, new ByteArrayInputStream(buf), TransferOperation.UPLOAD, new EventMetadata()); } catch (IndyWorkflowException e) { e.printStackTrace(); Assert.fail("failed to store generated file to: " + source + path); } }); } catch (IndyDataException e) { e.printStackTrace(); Assert.fail("failed to store hosted repository: " + source); } }); final HostedRepository target = new HostedRepository(MAVEN_PKG_KEY, "target"); storeManager.storeArtifactStore(target, new ChangeSummary(ChangeSummary.SYSTEM_USER, "test setup"), false, true, new EventMetadata()); PathsPromoteResult[] results = new PathsPromoteResult[2]; CountDownLatch cdl = new CountDownLatch(2); AtomicInteger counter = new AtomicInteger(0); Stream.of(sources).forEach((source) -> { int idx = counter.getAndIncrement(); executor.execute(() -> { try { results[idx] = manager.promotePaths( new PathsPromoteRequest(source.getKey(), target.getKey(), paths), FAKE_BASE_URL); } catch (Exception e) { e.printStackTrace(); Assert.fail("Promotion from source: " + source + " failed."); } finally { cdl.countDown(); } }); try { Thread.sleep(25); } catch (InterruptedException e) { Assert.fail("Test interrupted"); } }); assertThat("Promotions failed to finish.", cdl.await(30, TimeUnit.SECONDS), equalTo(true)); // first one should succeed. PathsPromoteResult result = results[0]; assertThat(result.getRequest().getSource(), equalTo(sources[0].getKey())); assertThat(result.getRequest().getTarget(), equalTo(target.getKey())); Set<String> pending = result.getPendingPaths(); assertThat(pending == null || pending.isEmpty(), equalTo(true)); Set<String> skipped = result.getSkippedPaths(); assertThat(skipped == null || skipped.isEmpty(), equalTo(true)); Set<String> completed = result.getCompletedPaths(); assertThat(completed, notNullValue()); assertThat(completed.size(), equalTo(paths.length)); assertThat(result.getError(), nullValue()); Stream.of(paths).forEach((path) -> { HostedRepository src = sources[0]; Transfer sourceRef = downloadManager.getStorageReference(src, path); Transfer targetRef = downloadManager.getStorageReference(target, path); assertThat(targetRef.exists(), equalTo(true)); try (InputStream sourceIn = sourceRef.openInputStream(); InputStream targetIn = targetRef.openInputStream()) { int s = -1, t = -1; while ((s = sourceIn.read()) == (t = targetIn.read())) { if (s == -1) { break; } } if (s != -1 && s != t) { Assert.fail(path + " doesn't match between source: " + src + " and target: " + target); } } catch (IOException e) { e.printStackTrace(); Assert.fail("Failed to compare contents of: " + path + " between source: " + src + " and target: " + target); } }); // second one should be completely skipped. result = results[1]; assertThat(result.getRequest().getSource(), equalTo(sources[1].getKey())); assertThat(result.getRequest().getTarget(), equalTo(target.getKey())); pending = result.getPendingPaths(); assertThat(pending == null || pending.isEmpty(), equalTo(true)); skipped = result.getSkippedPaths(); assertThat(skipped, notNullValue()); assertThat(skipped.size(), equalTo(paths.length)); completed = result.getCompletedPaths(); assertThat(completed == null || completed.isEmpty(), equalTo(true)); assertThat(result.getError(), nullValue()); }
From source file:org.apache.camel.processor.LoopProcessor.java
protected boolean process(final Exchange exchange, final AsyncCallback callback, final AtomicInteger index, final AtomicInteger count) { // set current index as property if (LOG.isDebugEnabled()) { LOG.debug("LoopProcessor: iteration #" + index.get()); }/* w w w . j ava 2 s . c om*/ exchange.setProperty(Exchange.LOOP_INDEX, index.get()); boolean sync = processNext(exchange, new AsyncCallback() { public void done(boolean doneSync) { // we only have to handle async completion of the routing slip if (doneSync) { return; } // increment index as we have just processed once index.getAndIncrement(); // continue looping asynchronously while (index.get() < count.get()) { // and prepare for next iteration ExchangeHelper.prepareOutToIn(exchange); // process again boolean sync = process(exchange, callback, index, count); if (!sync) { if (LOG.isTraceEnabled()) { LOG.trace("Processing exchangeId: " + exchange.getExchangeId() + " is continued being processed asynchronously"); } // the remainder of the routing slip will be completed async // so we break out now, then the callback will be invoked which then continue routing from where we left here return; } // increment counter before next loop index.getAndIncrement(); } // we are done so prepare the result ExchangeHelper.prepareOutToIn(exchange); if (LOG.isTraceEnabled()) { LOG.trace( "Processing complete for exchangeId: " + exchange.getExchangeId() + " >>> " + exchange); } callback.done(false); } }); return sync; }
From source file:org.easyrec.plugin.slopeone.impl.SlopeOneServiceImpl.java
public void nonPersonalizedRecommendations(final SlopeOneIntegerConfiguration config, final SlopeOneStats stats, final Date execution, final Set<TenantItem> changedItemIds, final ExecutionControl control) { final long start = System.currentTimeMillis(); final int MAX_ITEMASSOCS = 50000; // atomic to support usage in changedItemIds.forEach(AnonymousClass) final AtomicInteger itemAssocCount = new AtomicInteger(0); final int TOTAL_STEPS = changedItemIds.size(); // atomic to support usage in changedItemIds.forEach(AnonymousClass) final AtomicInteger currentStep = new AtomicInteger(0); Integer maxRecsPerItem = config.getMaxRecsPerItem(); final List<ItemAssocVO<Integer, Integer>> itemAssocs = new ArrayList<ItemAssocVO<Integer, Integer>>( Math.min(changedItemIds.size() * (maxRecsPerItem != null ? maxRecsPerItem : 10), MAX_ITEMASSOCS)); for (TenantItem changedItem : changedItemIds) { if (control != null) control.updateProgress(String.format("Calculating non-personalized recommendations %d/%d", currentStep.getAndIncrement(), TOTAL_STEPS)); List<Deviation> deviations = deviationDAO.getDeviationsOrdered(config.getTenant(), changedItem.getItemTypeId(), changedItem.getItemId(), config.getMinRatedCount(), config.getMaxRecsPerItem()); for (Deviation deviation : deviations) { ItemAssocVO<Integer, Integer> assoc = new ItemAssocVO<Integer, Integer>(config.getTenant(), deviation.getItem1(), config.getAssocType(), deviation.getDeviation(), deviation.getItem2(), config.getSourceType(), config.getNonPersonalizedSourceInfo(), config.getViewType(), Boolean.TRUE, execution); itemAssocs.add(assoc);/*from ww w . jav a2 s . c om*/ } if (itemAssocs.size() >= MAX_ITEMASSOCS) { itemAssocCount.getAndAdd((itemAssocs.size())); itemAssocDAO.insertOrUpdateItemAssocs(itemAssocs); itemAssocs.clear(); } } if (itemAssocs.size() > 0) { itemAssocCount.getAndAdd((itemAssocs.size())); itemAssocDAO.insertOrUpdateItemAssocs(itemAssocs); itemAssocs.clear(); } itemAssocDAO.removeItemAssocByTenant(config.getTenant(), config.getAssocType(), config.getSourceType(), execution); stats.setNumberOfRulesCreated(itemAssocCount.get()); stats.setNonPersonalizedDuration(System.currentTimeMillis() - start); }