List of usage examples for java.util.concurrent.atomic AtomicInteger incrementAndGet
public final int incrementAndGet()
From source file:org.apache.hadoop.hbase.client.AsyncProcess.java
/** * increment the tasks counters for a given set of regions. MT safe. *///from w w w . ja v a 2 s .c om protected void incTaskCounters(Collection<byte[]> regions, ServerName sn) { tasksInProgress.incrementAndGet(); AtomicInteger serverCnt = taskCounterPerServer.get(sn); if (serverCnt == null) { taskCounterPerServer.putIfAbsent(sn, new AtomicInteger()); serverCnt = taskCounterPerServer.get(sn); } serverCnt.incrementAndGet(); for (byte[] regBytes : regions) { AtomicInteger regionCnt = taskCounterPerRegion.get(regBytes); if (regionCnt == null) { regionCnt = new AtomicInteger(); AtomicInteger oldCnt = taskCounterPerRegion.putIfAbsent(regBytes, regionCnt); if (oldCnt != null) { regionCnt = oldCnt; } } regionCnt.incrementAndGet(); } }
From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java
@Test public void shouldDecodeOneRowResponseWithQuotesInClientIdAndResults() throws Exception { String expectedClientIdWithQuotes = "ThisIsA\\\"Client\\\"Id"; String response = Resources.read("with_escaped_quotes.json", this.getClass()); HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK")); HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8)); GenericQueryRequest requestMock = mock(GenericQueryRequest.class); queue.add(requestMock);//from ww w. j a va2 s. c o m channel.writeInbound(responseHeader, responseChunk); latch.await(1, TimeUnit.SECONDS); assertEquals(1, firedEvents.size()); GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0); final AtomicInteger invokeCounter1 = new AtomicInteger(); assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, expectedClientIdWithQuotes, "success", FAKE_SIGNATURE, new Action1<ByteBuf>() { @Override public void call(ByteBuf buf) { invokeCounter1.incrementAndGet(); String response = buf.toString(CharsetUtil.UTF_8); try { Map found = mapper.readValue(response, Map.class); assertEquals(12, found.size()); assertEquals("San Francisco", found.get("city")); assertEquals("United States", found.get("country")); Map geo = (Map) found.get("geo"); assertNotNull(geo); assertEquals(3, geo.size()); assertEquals("ROOFTOP", geo.get("accuracy")); //TODO check the quote in the result } catch (IOException e) { assertFalse(true); } } }, new Action1<ByteBuf>() { @Override public void call(ByteBuf buf) { fail("no error expected"); } }, expectedMetricsCounts(0, 1)); assertEquals(1, invokeCounter1.get()); }
From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java
@Test public void shouldDecodeArrayAsSignature() throws Exception { String response = Resources.read("signature_array.json", this.getClass()); HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK")); HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8)); GenericQueryRequest requestMock = mock(GenericQueryRequest.class); queue.add(requestMock);/*from w ww .j a v a 2 s . co m*/ channel.writeInbound(responseHeader, responseChunk); latch.await(1, TimeUnit.SECONDS); assertEquals(1, firedEvents.size()); GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0); final AtomicInteger invokeCounter1 = new AtomicInteger(); assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, FAKE_CLIENTID, "success", "[\"json\",\"array\",[\"sub\",true]]", new Action1<ByteBuf>() { @Override public void call(ByteBuf buf) { invokeCounter1.incrementAndGet(); String item = buf.toString(CharsetUtil.UTF_8); buf.release(); fail("no result expected, got " + item); } }, new Action1<ByteBuf>() { @Override public void call(ByteBuf buf) { buf.release(); fail("no error expected"); } }, //no metrics in this json sample expectedMetricsCounts(0, 1)); assertEquals(0, invokeCounter1.get()); }
From source file:org.apache.directory.studio.test.integration.ui.BrowserTest.java
/** * Test for DIRSTUDIO-1121./*from ww w. j a va 2 s . c om*/ * * Verify input is set only once when entry is selected. */ @Test public void testSetInputOnlyOnce() throws Exception { browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users"); browserViewBot.expandEntry("DIT", "Root DSE", "ou=system", "ou=users"); // verify link-with-editor is enabled assertTrue(BrowserUIPlugin.getDefault().getPreferenceStore() .getBoolean(BrowserUIConstants.PREFERENCE_BROWSER_LINK_WITH_EDITOR)); // setup counter and listener to record entry editor input changes final AtomicInteger counter = new AtomicInteger(); UIThreadRunnable.syncExec(new VoidResult() { public void run() { try { IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActiveEditor(); editor.addPropertyListener(new IPropertyListener() { @Override public void propertyChanged(Object source, int propId) { if (source instanceof EntryEditor && propId == BrowserUIConstants.INPUT_CHANGED) { counter.incrementAndGet(); } } }); } catch (Exception e) { throw new RuntimeException(e); } } }); // select 3 different entries, select one twice should not set the input again browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.1"); browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.1"); browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.2"); browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.2"); browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.3"); browserViewBot.selectEntry("DIT", "Root DSE", "ou=system", "ou=users", "uid=user.3"); // verify that input was only set 3 times. assertEquals("Only 3 input changes expected.", 3, counter.get()); // reset counter counter.set(0); // use navigation history to go back and forth, each step should set input only once studioBot.navigationHistoryBack(); browserViewBot.waitUntilEntryIsSelected("uid=user.2"); studioBot.navigationHistoryBack(); browserViewBot.waitUntilEntryIsSelected("uid=user.1"); studioBot.navigationHistoryForward(); browserViewBot.waitUntilEntryIsSelected("uid=user.2"); studioBot.navigationHistoryForward(); browserViewBot.waitUntilEntryIsSelected("uid=user.3"); // verify that input was only set 4 times. assertEquals("Only 4 input changes expected.", 4, counter.get()); }
From source file:io.fabric8.example.calculator.msg.RequestReplyTest.java
@Test public void theTest() throws Exception { PooledConnectionFactory connectionFactory = new PooledConnectionFactory(); connectionFactory.setConnectionFactory(new ActiveMQConnectionFactory("failover:(tcp://localhost:61616)")); final AtomicInteger counter = new AtomicInteger(); CamelContext serviceContext = new DefaultCamelContext(); serviceContext.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory)); serviceContext.addRoutes(new RouteBuilder() { @Override//from www . j a va 2 s .co m public void configure() throws Exception { RandomGenerator rg = new JDKRandomGenerator(); int num = rg.nextInt(); from("jms:myQueue.queue") // .setHeader("JMSMessageID", constant("ID : " + num)) // .setHeader("JMSReplyTo", constant("myQueue.queue")) .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); /*** * Process data and get the response and set the resposen to the Exchage * body. */ exchange.getOut().setBody("RESPONSE " + counter.incrementAndGet()); } }); } }); serviceContext.start(); CamelContext requestorContext = new DefaultCamelContext(); requestorContext.addComponent("jms", ActiveMQComponent.jmsComponentAutoAcknowledge(connectionFactory)); requestorContext.start(); ProducerTemplate producerTemplate = requestorContext.createProducerTemplate(); for (int i = 0; i < 1000; i++) { Object response = producerTemplate .requestBodyAndHeader( "jms:myQueue.queue?exchangePattern=InOut&requestTimeout=40000&timeToLive=40000" + "&asyncConsumer=true&asyncStartListener=true&concurrentConsumers=10" + "&useMessageIDAsCorrelationID=true", "mBodyMsg", "HeaderString", "HeaderValue"); System.err.println("RESPONSE = " + response); } requestorContext.stop(); serviceContext.stop(); }
From source file:com.bt.aloha.util.ConcurrentUpdateManagerTest.java
@Test public void testConcurrentUpdateConflictAwawreExceptionAbsorbed() throws Exception { // setup/* w ww . ja va2 s . c o m*/ final CountDownLatch firstWriterRead = new CountDownLatch(1); final CountDownLatch secondWriterWrote = new CountDownLatch(1); final AtomicInteger failuresCounter = new AtomicInteger(); ConcurrentUpdateBlock concurrentUpdateBlock = new ConflictAwareConcurrentUpdateBlock() { public void execute() { DialogInfo di = dialogCollection.get(dialogId); log.debug("First writer read"); firstWriterRead.countDown(); di.setApplicationData("first"); log.debug("Waiting for second writer to write"); try { secondWriterWrote.await(); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } dialogCollection.replace(di); log.debug("First writer replaced"); } public String getResourceId() { return dialogId; } public void onConcurrentUpdateConflict() { failuresCounter.incrementAndGet(); throw new RuntimeException("bugger off"); } }; Runnable competingWriter = new Runnable() { public void run() { log.debug("Waiting for first writer to read"); try { firstWriterRead.await(); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } DialogInfo di = dialogCollection.get(dialogId); di.setApplicationData("second"); dialogCollection.replace(di); log.debug("Second writer replaced"); secondWriterWrote.countDown(); } }; // act new Thread(competingWriter).start(); concurrentUpdateManager.executeConcurrentUpdate(concurrentUpdateBlock); // assert assertEquals(1, failuresCounter.get()); assertEquals("first", dialogCollection.get(dialogId).getApplicationData()); }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTest.java
@Test public void shouldReloadClassLoaderWhileDoingEvalInSeparateThread() throws Exception { final AtomicBoolean fail = new AtomicBoolean(false); final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Color> color = new AtomicReference<>(Color.RED); final GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine(); try {//from w w w . j ava 2 s .c o m scriptEngine.eval("Color.BLACK"); fail("Should fail as class is not yet imported"); } catch (ScriptException se) { // should get here as Color.BLACK is not imported yet. logger.info("Failed to execute Color.BLACK as expected."); } final Thread evalThread = new Thread(() -> { try { // execute scripts until the other thread releases this latch (i.e. after import) while (latch.getCount() == 1) { scriptEngine.eval("1+1"); counter.incrementAndGet(); } color.set((Color) scriptEngine.eval("Color.BLACK")); } catch (Exception se) { fail.set(true); } }, "test-reload-classloader-1"); evalThread.start(); // let the first thread execute a bit. Thread.sleep(1000); final Thread importThread = new Thread(() -> { logger.info("Importing java.awt.Color..."); final Set<String> imports = new HashSet<String>() { { add("import java.awt.Color"); } }; scriptEngine.addImports(imports); latch.countDown(); }, "test-reload-classloader-2"); importThread.start(); // block until both threads are done importThread.join(); evalThread.join(); assertEquals(Color.BLACK, color.get()); assertThat(counter.get(), greaterThan(0)); assertFalse(fail.get()); }
From source file:com.streamsets.pipeline.stage.origin.spooldir.TestSpoolDirSource.java
private void readFilesMultipleThreads(String spoolDir, int numberOfThreads) throws Exception { SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.TEXT;/*from w ww. j a va 2s .c o m*/ conf.spoolDir = spoolDir; conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 1; conf.filePattern = "*file-[0-9].log"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.initialFileToProcess = null; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; conf.allowLateDirectory = false; conf.numberOfThreads = numberOfThreads; SpoolDirSource source = new SpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane") .build(); AtomicInteger batchCount = new AtomicInteger(0); final List<Record> records = Collections.synchronizedList(new ArrayList<>(10)); runner.runInit(); final int maxBatchSize = 10; try { runner.runProduce(new HashMap<>(), maxBatchSize, output -> { batchCount.incrementAndGet(); synchronized (records) { records.addAll(output.getRecords().get("lane")); } if (records.size() == 50 || batchCount.get() > 10) { runner.setStop(); } }); runner.waitOnProduce(); Assert.assertTrue(batchCount.get() > 1); TestOffsetUtil.compare("-file-9.log::-1", runner.getOffsets()); Assert.assertEquals(50, records.size()); } finally { runner.runDestroy(); } }
From source file:org.jtheque.file.FileServiceTest.java
@Test @DirtiesContext//from w w w . ja v a 2 s . c o m public void restore() { File backupFile = new File(SystemProperty.USER_DIR.get(), "backup.xml"); createFakeBackupFile(backupFile); final AtomicInteger counter = new AtomicInteger(0); fileService.registerBackuper("no-module", new ModuleBackuper() { @Override public String getId() { return "test-backup"; } @Override public String[] getDependencies() { return new String[0]; } @Override public ModuleBackup backup() { fail("Backup must not be called"); return null; } @Override public void restore(ModuleBackup backup) { assertEquals("test-backup", backup.getId()); assertEquals(Version.get("1.0"), backup.getVersion()); assertEquals(1, backup.getNodes().size()); for (org.jtheque.xml.utils.Node node : backup.getNodes()) { assertEquals("simple", node.getName()); assertEquals("true", node.getAttributeValue("test")); } counter.incrementAndGet(); } }); try { fileService.restore(backupFile); } catch (XMLException e) { fail(e.getMessage()); } assertEquals(1, counter.get()); }
From source file:de.undercouch.bson4jackson.BsonParserTest.java
/** * Tests reading a very large string using multiple threads. Refers * issue #19. Does not fail reproducibly, but with very high probability. * You may have to run unit tests several times though to really rule out * multi-threading issues.//from w w w .ja v a 2s . c o m * @throws Exception if something went wrong * @author endasb */ @Test public void parseBigStringInThreads() throws Exception { final BSONObject o = new BasicBSONObject(); final AtomicInteger fails = new AtomicInteger(0); StringBuilder bigStr = new StringBuilder(); for (int i = 0; i < 80000; i++) { bigStr.append("abc"); } o.put("String", bigStr.toString()); ArrayList<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 50; i++) { threads.add(new Thread(new Runnable() { @Override public void run() { try { Map<?, ?> data = parseBsonObject(o); data = parseBsonObject(o); assertNotNull(data); } catch (Exception e) { fail("Threading issue " + fails.incrementAndGet()); } } })); } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } assertEquals(0, fails.get()); }