List of usage examples for java.util.concurrent.atomic AtomicInteger set
public final void set(int newValue)
From source file:org.apache.hedwig.server.delivery.TestThrottlingDelivery.java
private void throttleX(Publisher pub, final Subscriber sub, ByteString topic, ByteString subid, final int X) throws Exception { for (int i = 1; i <= 3 * X; i++) { pub.publish(topic, Message.newBuilder().setBody(ByteString.copyFromUtf8(String.valueOf(i))).build()); }//www .j a v a 2 s . co m SubscriptionOptions opts = SubscriptionOptions.newBuilder().setCreateOrAttach(CreateOrAttach.ATTACH) .build(); sub.subscribe(topic, subid, opts); final AtomicInteger expected = new AtomicInteger(1); final CountDownLatch throttleLatch = new CountDownLatch(1); final CountDownLatch nonThrottleLatch = new CountDownLatch(1); sub.startDelivery(topic, subid, new MessageHandler() { @Override public synchronized void deliver(ByteString topic, ByteString subscriberId, Message msg, Callback<Void> callback, Object context) { try { int value = Integer.valueOf(msg.getBody().toStringUtf8()); logger.debug("Received message {},", value); if (value == expected.get()) { expected.incrementAndGet(); } else { // error condition logger.error("Did not receive expected value, expected {}, got {}", expected.get(), value); expected.set(0); throttleLatch.countDown(); nonThrottleLatch.countDown(); } if (expected.get() > X + 1) { throttleLatch.countDown(); } if (expected.get() == (3 * X + 1)) { nonThrottleLatch.countDown(); } callback.operationFinished(context, null); if (expected.get() > X + 1) { sub.consume(topic, subscriberId, msg.getMsgId()); } } catch (Exception e) { logger.error("Received bad message", e); throttleLatch.countDown(); nonThrottleLatch.countDown(); } } }); assertFalse("Received more messages than throttle value " + X, throttleLatch.await(3, TimeUnit.SECONDS)); assertEquals("Should be expected messages with only " + (X + 1), X + 1, expected.get()); // consume messages to not throttle it for (int i = 1; i <= X; i++) { sub.consume(topic, subid, MessageSeqId.newBuilder().setLocalComponent(i).build()); } assertTrue("Timed out waiting for messages " + (3 * X + 1), nonThrottleLatch.await(10, TimeUnit.SECONDS)); assertEquals("Should be expected message with " + (3 * X + 1), 3 * X + 1, expected.get()); sub.stopDelivery(topic, subid); sub.closeSubscription(topic, subid); }
From source file:com.netflix.curator.framework.imps.TestFrameworkEdges.java
@Test public void testRetry() throws Exception { final int MAX_RETRIES = 3; final int serverPort = server.getPort(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 1000, 1000, new RetryOneTime(10)); client.start();//from w w w . j a v a 2s . co m try { final AtomicInteger retries = new AtomicInteger(0); final Semaphore semaphore = new Semaphore(0); client.getZookeeperClient().setRetryPolicy(new RetryPolicy() { @Override public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { semaphore.release(); if (retries.incrementAndGet() == MAX_RETRIES) { try { server = new TestingServer(serverPort); } catch (Exception e) { throw new Error(e); } } return true; } }); server.stop(); // test foreground retry client.checkExists().forPath("/hey"); Assert.assertTrue(semaphore.tryAcquire(MAX_RETRIES, 10, TimeUnit.SECONDS)); semaphore.drainPermits(); retries.set(0); server.stop(); // test background retry client.checkExists().inBackground().forPath("/hey"); Assert.assertTrue(semaphore.tryAcquire(MAX_RETRIES, 10, TimeUnit.SECONDS)); } catch (Throwable e) { Assert.fail("Error", e); } finally { IOUtils.closeQuietly(client); } }
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;//from w ww . j av a 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:org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexAugmentTest.java
@Test public void indexHookCallbackFrequency() throws Exception { //setup repo and index NodeTypeRegistry.register(root, IOUtils.toInputStream(TestUtil.TEST_NODE_TYPE), "test nodeType"); Tree props = createIndex(TestUtil.NT_TEST); TestUtil.enablePropertyIndex(props, "foo1", false); TestUtil.enablePropertyIndex(props, "foo2", false); TestUtil.enablePropertyIndex(props, "subChild/foo3", false); root.commit();// w ww .java 2 s.c o m //setup index augmentor final AtomicInteger counter = new AtomicInteger(0); factory.indexFieldProvider = new IndexFieldProvider() { @Nonnull @Override public Iterable<Field> getAugmentedFields(String path, NodeState document, NodeState indexDefinition) { counter.incrementAndGet(); return IndexFieldProvider.DEFAULT.getAugmentedFields(path, document, indexDefinition); } @Nonnull @Override public Set<String> getSupportedTypes() { return Collections.singleton(TestUtil.NT_TEST); } }; //add content counter.set(0); Tree test = root.getTree("/").addChild("test"); Tree node = createNodeWithType(test, "item", TestUtil.NT_TEST); node.setProperty("foo1", "bar1"); node.setProperty("foo2", "bar2"); Tree subChild = node.addChild("subChild"); subChild.setProperty("foo3", "bar3"); root.commit(); assertEquals("Number of callbacks should be same as number of changed properties", 1, counter.get()); //change sub-property counter.set(0); subChild = root.getTree("/test/item/subChild"); subChild.setProperty("foo3", "bar4"); root.commit(); assertEquals("Sub child property change should make call backs for all indexed properties", 1, counter.get()); }
From source file:byps.test.TestRemoteServerR.java
private void internalCallClientAsync(ServerIFAsync remote, int value, final AtomicInteger r1, final AtomicReference<Throwable> ex, final CountDownLatch countDown) { remote.callClientIncrementInt(value, new BAsyncResult<Integer>() { public void setAsyncResult(Integer result, Throwable exception) { if (exception != null) { ex.set(exception);// w w w . j av a2 s .co m } else { r1.set(result); } countDown.countDown(); } }); }
From source file:com.facebook.BatchRequestTests.java
@LargeTest public void testBatchLastOnProgressCallbackIsCalledOnce() { final AtomicInteger count = new AtomicInteger(); final AccessToken accessToken = getAccessTokenForSharedUser(); String appId = getApplicationId(); GraphRequest.setDefaultBatchApplicationId(appId); GraphRequest request1 = GraphRequest.newGraphPathRequest(accessToken, "4", null); assertNotNull(request1);//from w w w .ja v a2s . c om GraphRequest request2 = GraphRequest.newGraphPathRequest(accessToken, "4", null); assertNotNull(request2); GraphRequestBatch batch = new GraphRequestBatch(request1, request2); batch.addCallback(new GraphRequestBatch.OnProgressCallback() { @Override public void onBatchCompleted(GraphRequestBatch batch) { } @Override public void onBatchProgress(GraphRequestBatch batch, long current, long max) { if (current == max) { count.incrementAndGet(); } else if (current > max) { count.set(0); } } }); batch.executeAndWait(); assertEquals(1, count.get()); }
From source file:org.gridgain.grid.kernal.processors.ggfs.GridGgfsProcessorSelfTest.java
/** * Test make directories in multi-threaded environment. * * @throws Exception In case of any exception. *//*from w w w. java 2s . c o m*/ @SuppressWarnings("TooBroadScope") public void testMakeListDeleteDirsMultithreaded() throws Exception { assertListDir("/"); final int max = 2 * 1000; final int threads = 50; final AtomicInteger cnt = new AtomicInteger(); info("Create directories: " + max); GridTestUtils.runMultiThreaded(new Callable<Object>() { @Override public Object call() throws Exception { for (int cur = cnt.incrementAndGet(); cur < max; cur = cnt.incrementAndGet()) ggfs.mkdirs(path(cur)); return null; } }, threads, "grid-test-make-directories"); info("Validate directories were created."); cnt.set(0); // Reset counter. GridTestUtils.runMultiThreaded(new Callable<Object>() { @Override public Object call() throws Exception { for (int cur = cnt.incrementAndGet(); cur < max; cur = cnt.incrementAndGet()) { GridGgfsFile info = ggfs.info(path(cur)); assertNotNull("Expects file exist: " + cur, info); assertTrue("Expects file is a directory: " + cur, info.isDirectory()); } return null; } }, threads, "grid-test-check-directories-exist"); info("Validate directories removing."); cnt.set(0); // Reset counter. GridTestUtils.runMultiThreaded(new Callable<Object>() { @Override public Object call() throws Exception { for (int cur = cnt.incrementAndGet(); cur < max; cur = cnt.incrementAndGet()) ggfs.delete(path(cur), true); return null; } }, threads, "grid-test-delete-directories"); }
From source file:com.facebook.BatchRequestTests.java
@LargeTest public void testMixedBatchCallbacks() { final AtomicInteger requestProgressCount = new AtomicInteger(); final AtomicInteger requestCompletedCount = new AtomicInteger(); final AtomicInteger batchProgressCount = new AtomicInteger(); final AtomicInteger batchCompletedCount = new AtomicInteger(); final AccessToken accessToken = getAccessTokenForSharedUser(); String appId = getApplicationId(); GraphRequest.setDefaultBatchApplicationId(appId); GraphRequest request1 = GraphRequest.newGraphPathRequest(null, "4", new GraphRequest.OnProgressCallback() { @Override/*from w ww .j av a 2s. c om*/ public void onCompleted(GraphResponse response) { requestCompletedCount.incrementAndGet(); } @Override public void onProgress(long current, long max) { if (current == max) { requestProgressCount.incrementAndGet(); } else if (current > max) { requestProgressCount.set(0); } } }); assertNotNull(request1); GraphRequest request2 = GraphRequest.newGraphPathRequest(null, "4", null); assertNotNull(request2); GraphRequestBatch batch = new GraphRequestBatch(request1, request2); batch.addCallback(new GraphRequestBatch.OnProgressCallback() { @Override public void onBatchCompleted(GraphRequestBatch batch) { batchCompletedCount.incrementAndGet(); } @Override public void onBatchProgress(GraphRequestBatch batch, long current, long max) { if (current == max) { batchProgressCount.incrementAndGet(); } else if (current > max) { batchProgressCount.set(0); } } }); batch.executeAndWait(); assertEquals(1, requestProgressCount.get()); assertEquals(1, requestCompletedCount.get()); assertEquals(1, batchProgressCount.get()); assertEquals(1, batchCompletedCount.get()); }
From source file:org.apache.ignite.internal.processors.igfs.IgfsProcessorSelfTest.java
/** * Test make directories in multi-threaded environment. * * @throws Exception In case of any exception. *//*from w w w .j av a2 s .c o m*/ @SuppressWarnings("TooBroadScope") public void testMakeListDeleteDirsMultithreaded() throws Exception { assertListDir("/"); final int max = 2 * 1000; final int threads = 50; final AtomicInteger cnt = new AtomicInteger(); info("Create directories: " + max); GridTestUtils.runMultiThreaded(new Callable<Object>() { @Override public Object call() throws Exception { for (int cur = cnt.incrementAndGet(); cur < max; cur = cnt.incrementAndGet()) igfs.mkdirs(path(cur)); return null; } }, threads, "grid-test-make-directories"); info("Validate directories were created."); cnt.set(0); // Reset counter. GridTestUtils.runMultiThreaded(new Callable<Object>() { @Override public Object call() throws Exception { for (int cur = cnt.incrementAndGet(); cur < max; cur = cnt.incrementAndGet()) { IgfsFile info = igfs.info(path(cur)); assertNotNull("Expects file exist: " + cur, info); assertTrue("Expects file is a directory: " + cur, info.isDirectory()); } return null; } }, threads, "grid-test-check-directories-exist"); info("Validate directories removing."); cnt.set(0); // Reset counter. GridTestUtils.runMultiThreaded(new Callable<Object>() { @Override public Object call() throws Exception { for (int cur = cnt.incrementAndGet(); cur < max; cur = cnt.incrementAndGet()) igfs.delete(path(cur), true); return null; } }, threads, "grid-test-delete-directories"); }
From source file:org.eclipse.jubula.client.core.ClientTestImpl.java
/** {@inheritDoc} */ public void startTestJob(ITestJobPO testJob, Locale locale, boolean autoScreenshot, String noRunOptMode) { TestExecution.getInstance().setStartedTestJob(testJob); m_testjobStartTime = new Date(); try {//from w w w.j a va 2 s . c o m final AtomicBoolean isTestExecutionFailed = new AtomicBoolean(false); final AtomicInteger testExecutionMessageId = new AtomicInteger(0); final AtomicInteger testExecutionState = new AtomicInteger(0); final AtomicBoolean isTestExecutionFinished = new AtomicBoolean(false); ITestExecutionEventListener executionListener = new ITestExecutionEventListener() { /** {@inheritDoc} */ public void stateChanged(TestExecutionEvent event) { testExecutionState.set(event.getState().ordinal()); if (event.getState() == State.TEST_EXEC_FAILED) { if (event.getException() instanceof JBException) { JBException e = (JBException) event.getException(); testExecutionMessageId.set(e.getErrorId()); } isTestExecutionFailed.set(true); testExecutionFinished(); } } /** {@inheritDoc} */ public void endTestExecution() { testExecutionFinished(); } private void testExecutionFinished() { isTestExecutionFinished.set(true); removeTestExecutionEventListener(this); } }; List<INodePO> refTestSuiteList = testJob.getUnmodifiableNodeList(); for (INodePO node : refTestSuiteList) { IRefTestSuitePO refTestSuite = (IRefTestSuitePO) node; isTestExecutionFailed.set(false); isTestExecutionFinished.set(false); addTestExecutionEventListener(executionListener); AutIdentifier autId = new AutIdentifier(refTestSuite.getTestSuiteAutID()); startTestSuite(refTestSuite.getTestSuite(), locale, autId, autoScreenshot, null, noRunOptMode); while (!isTestExecutionFinished.get()) { TimeUtil.delay(500); } if (!continueTestJobExecution(testExecutionState, testExecutionMessageId)) { break; } } } finally { TestExecution.getInstance().setStartedTestJob(null); } }