List of usage examples for java.util.concurrent.atomic AtomicInteger get
public final int get()
From source file:org.chromium.android_webview.test.AwContentsTest.java
private int callDocumentHasImagesSync(final AwContents awContents) throws Throwable, InterruptedException { // Set up a container to hold the result object and a semaphore to // make the test wait for the result. final AtomicInteger val = new AtomicInteger(); final Semaphore s = new Semaphore(0); final Message msg = Message.obtain(new Handler(Looper.getMainLooper()) { @Override/*from ww w . j av a 2 s .com*/ public void handleMessage(Message msg) { val.set(msg.arg1); s.release(); } }); runTestOnUiThread(new Runnable() { @Override public void run() { awContents.documentHasImages(msg); } }); assertTrue(s.tryAcquire(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)); int result = val.get(); return result; }
From source file:org.apache.hadoop.hbase.client.TestAsyncTable.java
@Test public void testCheckAndDelete() throws InterruptedException, ExecutionException { AsyncTableBase table = getTable.get(); int count = 10; CountDownLatch putLatch = new CountDownLatch(count + 1); table.put(new Put(row).addColumn(FAMILY, QUALIFIER, VALUE)).thenRun(() -> putLatch.countDown()); IntStream.range(0, count)/*from w w w. j a v a2s . c om*/ .forEach(i -> table.put(new Put(row).addColumn(FAMILY, concat(QUALIFIER, i), VALUE)) .thenRun(() -> putLatch.countDown())); putLatch.await(); AtomicInteger successCount = new AtomicInteger(0); AtomicInteger successIndex = new AtomicInteger(-1); CountDownLatch deleteLatch = new CountDownLatch(count); IntStream.range(0, count).forEach(i -> table .checkAndDelete(row, FAMILY, QUALIFIER, VALUE, new Delete(row).addColumn(FAMILY, QUALIFIER).addColumn(FAMILY, concat(QUALIFIER, i))) .thenAccept(x -> { if (x) { successCount.incrementAndGet(); successIndex.set(i); } deleteLatch.countDown(); })); deleteLatch.await(); assertEquals(1, successCount.get()); Result result = table.get(new Get(row)).get(); IntStream.range(0, count).forEach(i -> { if (i == successIndex.get()) { assertFalse(result.containsColumn(FAMILY, concat(QUALIFIER, i))); } else { assertArrayEquals(VALUE, result.getValue(FAMILY, concat(QUALIFIER, i))); } }); }
From source file:com.jivesoftware.os.upena.service.UpenaStore.java
public void log(long whenAgoElapseLargestMillis, long whenAgoElapseSmallestMillis, int minCount, // final String who, final String what, final String why, final String where, final String how, final LogStream logStream) throws Exception { long time = System.currentTimeMillis(); final long maxTimestampInclusize = time - whenAgoElapseSmallestMillis; final long minTimestampExclusize = time - whenAgoElapseLargestMillis; final AtomicInteger count = new AtomicInteger(minCount); changeLogClient().scan(Collections.singletonList(ScanRange.ROW_SCAN), (byte[] prefix, byte[] key, byte[] value, long timestamp, long version) -> { RecordedChange change = mapper.readValue(value, RecordedChange.class); if (change.when <= maxTimestampInclusize && (change.when > minTimestampExclusize || count.get() > 0)) { if (who != null && who.length() > 0 && !change.who.contains(who)) { return true; }/*from ww w . j a v a 2s .c om*/ if (what != null && what.length() > 0 && !change.what.contains(what)) { return true; } if (why != null && why.length() > 0 && !change.why.contains(why)) { return true; } if (where != null && where.length() > 0 && !change.where.contains(where)) { return true; } if (how != null && how.length() > 0 && !change.how.contains(how)) { return true; } count.decrementAndGet(); return logStream.stream(change); } return change.when > maxTimestampInclusize || count.get() > 0; }, true); }
From source file:com.btoddb.chronicle.plunkers.HdfsPlunkerImplIT.java
@Test @Ignore("very flakey, need to work out a more stable way of testing") public void testLongRun() throws Exception { plunker.setIdleTimeout(0);/*from www. j av a2s . c om*/ plunker.setRollPeriod(2); plunker.setTimeoutCheckPeriod(100); plunker.init(config); final int sleep = 200; final int maxCount = 100; // 20 seconds at 'sleep' interval should be 10 files final AtomicInteger count = new AtomicInteger(); // do this to prime HDFS FileSystem object - otherwise timing is off plunker.handleInternal(Arrays.asList(new Event("the-body").withHeader("customer", "cust") .withHeader("msgId", String.valueOf(count.getAndIncrement())))); ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); System.out.println("start"); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { System.out.println("time = " + System.currentTimeMillis()); plunker.handleInternal(Arrays.asList(new Event("the-body").withHeader("customer", "cust") .withHeader("msgId", String.valueOf(count.get())))); } catch (Exception e) { e.printStackTrace(); } count.incrementAndGet(); } }, 0, sleep, TimeUnit.MILLISECONDS); while (count.get() < maxCount) { Thread.sleep(sleep / 2); } executor.shutdown(); executor.awaitTermination(60, TimeUnit.SECONDS); Thread.sleep(1500); plunker.shutdown(); Event[] events = new Event[count.get()]; for (int i = 0; i < count.get(); i++) { events[i] = new Event("the-body").withHeader("customer", "cust").withHeader("msgId", String.valueOf(i)); } File theDir = new File(String.format("%s/the/cust/path", baseDir.getPath())); assertThat(theDir, ftUtils.countWithSuffix(".tmp", 0)); assertThat(theDir, ftUtils.countWithSuffix(".avro", 10)); assertThat(theDir, ftUtils.hasEventsInDir(events)); }
From source file:ufo.remote.calls.benchmark.client.caller.activemq.ActiveMQTester.java
@Override protected void startTest(final TesterResult result) { ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); producerTemplate.setExecutorService(Executors.newFixedThreadPool(20)); String url = ActiveMQApacheCamelConfig.JMS_NAME + ":queue:echo?deliveryPersistent=false&replyToDeliveryPersistent=false"; AtomicInteger failures = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(result.totalCalls); for (int i = 0; i < result.totalCalls; i++) { producerTemplate.asyncCallbackRequestBody(url, result.message, new Synchronization() { @Override// w ww .ja v a2s.c o m public void onFailure(final Exchange exchange) { failures.incrementAndGet(); latch.countDown(); } @Override public void onComplete(final Exchange exchange) { if (logger.isDebugEnabled()) { logger.debug("Received message [{}]", exchange.getIn().getBody()); } latch.countDown(); } }); } try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } result.failures = failures.get(); }
From source file:ufo.remote.calls.benchmark.client.caller.hornetq.HornetQTester.java
@Override protected void startTest(final TesterResult result) { ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); producerTemplate.setExecutorService(Executors.newFixedThreadPool(20)); String url = HornetQApacheCamelConfig.JMS_NAME + ":queue:echo?deliveryPersistent=false&replyToDeliveryPersistent=false"; AtomicInteger failures = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(result.totalCalls); for (int i = 0; i < result.totalCalls; i++) { producerTemplate.asyncCallbackRequestBody(url, result.message, new Synchronization() { @Override/*from w w w . ja va 2 s . com*/ public void onFailure(final Exchange exchange) { failures.incrementAndGet(); latch.countDown(); } @Override public void onComplete(final Exchange exchange) { if (logger.isDebugEnabled()) { logger.debug("Received message [{}]", exchange.getIn().getBody()); } latch.countDown(); } }); } try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } result.failures = failures.get(); }
From source file:com.vmware.photon.controller.deployer.dcp.task.WaitForServiceTaskService.java
private void scheduleHealthCheckQuery(final State currentState, final HealthChecker healthChecker, final AtomicInteger retryCounter) { final Service service = this; Runnable runnable = new Runnable() { @Override//from w w w. ja va 2 s.c o m public void run() { if (retryCounter.decrementAndGet() < 0) { String errMessage = String.format("%s not ready after %s retries", currentState.containerType, currentState.maxRetries); ServiceUtils.logSevere(service, errMessage); failTask(new RuntimeException(errMessage)); return; } ServiceUtils.logInfo(service, "HealthCheck (%s) retry: %s of maxRetries(%s)", currentState.containerType, currentState.maxRetries - retryCounter.get(), currentState.maxRetries); if (healthChecker.isReady()) { sendStageProgressPatch(TaskState.TaskStage.FINISHED); return; } scheduleHealthCheckQuery(currentState, healthChecker, retryCounter); } }; getHost().schedule(runnable, currentState.taskPollDelay, TimeUnit.MILLISECONDS); }
From source file:dk.statsbiblioteket.util.JobControllerTest.java
public void testPopTimeout() throws Exception { final int JOBS = 10; final AtomicInteger counter = new AtomicInteger(0); JobController<Long> controller = new JobController<Long>(10) { @Override//from www . jav a 2 s. c o m protected void afterExecute(Future<Long> finished) { counter.incrementAndGet(); } }; for (int i = 0; i < JOBS; i++) { synchronized (Thread.currentThread()) { Thread.currentThread().wait(10); } controller.submit(new Shout(50)); } int allTimeout = controller.popAll(10, TimeUnit.MILLISECONDS).size(); int allLeft = controller.popAll().size(); assertTrue("Timeout popAll should be > 0 and < " + JOBS + " but was " + allTimeout, allTimeout > 0 && allTimeout < JOBS); assertEquals("The total pops should be correct", 10, allTimeout + allLeft); assertEquals("The callback count should be correct", 10, counter.get()); }
From source file:ws.antonov.config.consumer.ConfigClientTest.java
@SuppressWarnings({ "unchecked" }) public void testCachingConfigClientWrapper() throws Exception { FileInputStream fis = new FileInputStream("build/classes/test/config.pb"); final FlatConfigObject msg = FlatConfigObject.parseFrom(fis); final AtomicInteger accessCount = new AtomicInteger(0); ConfigClient client = new ConfigClient() { @Override/* w w w . j a v a 2 s. co m*/ public Message getConfig(Class configClass, ConfigParamsBuilder.ConfigParamsMap configParams) { accessCount.incrementAndGet(); if (configParams.size() == 0) return msg; else return null; } @Override public ConfigProvider getConfigProvider() { return null; } @Override public boolean reloadConfig() { return true; } }; Map objects = new HashMap(); Set keys = new HashSet(); CachingConfigClientWrapper cachingConfig = new CachingConfigClientWrapper(client, objects, keys); assertEquals(0, accessCount.get()); assertEquals(0, cachingConfig.getObjectCache().size()); assertEquals(0, cachingConfig.getNegativeCache().size()); assertEquals(cachingConfig.getConfig(FlatConfigObject.class, ConfigParamsBuilder.newInstance().build()), msg); assertEquals(1, accessCount.get()); assertEquals(1, cachingConfig.getObjectCache().size()); assertEquals(0, cachingConfig.getNegativeCache().size()); assertEquals(cachingConfig.getConfig(FlatConfigObject.class, ConfigParamsBuilder.newInstance().build()), msg); assertEquals(1, accessCount.get()); assertEquals(1, cachingConfig.getObjectCache().size()); assertEquals(0, cachingConfig.getNegativeCache().size()); assertNull(cachingConfig.getConfig(FlatConfigObject.class, ConfigParamsBuilder.newInstance("foo", "bar").build())); assertEquals(2, accessCount.get()); assertEquals(1, cachingConfig.getObjectCache().size()); assertEquals(1, cachingConfig.getNegativeCache().size()); assertNull(cachingConfig.getConfig(FlatConfigObject.class, ConfigParamsBuilder.newInstance("foo", "bar").build())); assertEquals(2, accessCount.get()); assertEquals(1, cachingConfig.getObjectCache().size()); assertEquals(1, cachingConfig.getNegativeCache().size()); }
From source file:com.github.cherimojava.data.mongo.io._DeEncoding.java
@Test public void saveDrop() { PrimitiveEntity pe = factory.create(PrimitiveEntity.class); factory.create(PrimitiveEntity.class).setString("don't delete").save(); pe.setString("413").save(); final AtomicInteger count = new AtomicInteger(0); MongoCollection<PrimitiveEntity> coll = getCollection(PrimitiveEntity.class); coll.find(PrimitiveEntity.class).forEach(new Block<Entity>() { @Override/*from ww w . ja v a2s . c o m*/ public void apply(Entity entity) { count.getAndIncrement(); } }); assertEquals(2, count.get()); pe.drop(); count.compareAndSet(2, 0); coll.find(PrimitiveEntity.class).forEach(new Block<Entity>() { @Override public void apply(Entity entity) { count.getAndIncrement(); } }); assertEquals(1, count.get()); }