List of usage examples for java.util.concurrent.atomic AtomicInteger AtomicInteger
public AtomicInteger(int initialValue)
From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaHttpClientDispatchTest.java
@Test public void testConnectivityFailover() throws Exception { String serviceName = "WEBHDFS"; HaDescriptor descriptor = HaDescriptorFactory.createDescriptor(); descriptor.addServiceConfig(//from ww w .j av a 2 s .c o m HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000")); HaProvider provider = new DefaultHaProvider(descriptor); URI uri1 = new URI("http://unreachable-host"); URI uri2 = new URI("http://reachable-host"); ArrayList<String> urlList = new ArrayList<String>(); urlList.add(uri1.toString()); urlList.add(uri2.toString()); provider.addHaService(serviceName, urlList); FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class); ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class); EasyMock.expect(filterConfig.getInitParameter(WebHdfsHaHttpClientDispatch.RESOURCE_ROLE_ATTRIBUTE)) .andReturn(serviceName).anyTimes(); EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes(); EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)) .andReturn(provider).anyTimes(); BasicHttpParams params = new BasicHttpParams(); HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class); EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes(); EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes(); EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes(); HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class); EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once(); EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)) .once(); EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)) .once(); HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() { @Override public ServletOutputStream answer() throws Throwable { return new ServletOutputStream() { @Override public void write(int b) throws IOException { throw new IOException("unreachable-host"); } }; } }).once(); EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse); Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName)); WebHdfsHaHttpClientDispatch dispatch = new WebHdfsHaHttpClientDispatch(); dispatch.init(filterConfig); long startTime = System.currentTimeMillis(); try { dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse); } catch (IOException e) { //this is expected after the failover limit is reached } long elapsedTime = System.currentTimeMillis() - startTime; Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName)); //test to make sure the sleep took place Assert.assertTrue(elapsedTime > 1000); }
From source file:org.jtheque.features.FeatureServiceTest.java
@Test public void listenerNotCalledAfterRemoved() { final AtomicInteger addCounter = new AtomicInteger(0); final AtomicInteger removeCounter = new AtomicInteger(0); final AtomicInteger modifyCounter = new AtomicInteger(0); FeatureListener listener = new MyFeatureListener(addCounter, removeCounter, modifyCounter); featureService.addFeatureListener(listener); featureService.addMenu("no-module", new MenuMain()); featureService.removeFeatureListener(listener); featureService.addMenu("no-module-2", new MenuMain()); assertEquals(1, addCounter.get());/*from w ww .ja va 2 s.co m*/ assertEquals(0, removeCounter.get()); assertEquals(0, modifyCounter.get()); }
From source file:com.splout.db.integration.TestMultiThreadedQueryAndDeploy.java
@Test @Ignore // Causes some non-deterministic problems, to be analyzed public void test() throws Throwable { FileUtils.deleteDirectory(new File(TMP_FOLDER)); new File(TMP_FOLDER).mkdirs(); createSploutEnsemble(N_QNODES, N_DNODES); String[] qNodeAddresses = new String[N_QNODES]; for (int i = 0; i < N_QNODES; i++) { qNodeAddresses[i] = getqNodes().get(i).getAddress(); }/*w ww.jav a 2 s . co m*/ final SploutClient client = new SploutClient(qNodeAddresses); final Tablespace testTablespace = createTestTablespace(N_DNODES); final Random random = new Random(SEED); final AtomicBoolean failed = new AtomicBoolean(false); final AtomicInteger iteration = new AtomicInteger(0); final Set<Integer> iterationsSeen = new HashSet<Integer>(); deployIteration(0, random, client, testTablespace); for (QNode qnode : getqNodes()) { // Make sure all QNodes are aware of the the first deploy // There might be some delay as they have to receive notifications via Hazelcast etc long waitedSoFar = 0; QueryStatus status = null; SploutClient perQNodeClient = new SploutClient(qnode.getAddress()); do { status = perQNodeClient.query(TABLESPACE, "0", "SELECT * FROM " + TABLE + ";", null); Thread.sleep(100); waitedSoFar += 100; if (waitedSoFar > 5000) { throw new AssertionError("Waiting too much on a test condition"); } } while (status == null || status.getError() != null); log.info("QNode [" + qnode.getAddress() + "] is ready to serve deploy 0."); } try { // Business logic here ExecutorService service = Executors.newFixedThreadPool(N_THREADS); // These threads will continuously perform queries and check that the results is consistent. // They will also count how many deploys have happened since the beginning. for (int i = 0; i < N_THREADS; i++) { service.submit(new Runnable() { @Override public void run() { try { while (true) { int randomDNode = Math.abs(random.nextInt()) % N_DNODES; QueryStatus status = client.query(TABLESPACE, (randomDNode * 10) + "", "SELECT * FROM " + TABLE + ";", null); log.info("Query status -> " + status); assertEquals(1, status.getResult().size()); Map<String, Object> jsonResult = (Map<String, Object>) status.getResult().get(0); Integer seenIteration = (Integer) jsonResult.get("iteration"); synchronized (iterationsSeen) { iterationsSeen.add(seenIteration); } assertTrue(seenIteration <= iteration.get()); assertEquals(randomDNode, jsonResult.get("dnode")); Thread.sleep(100); } } catch (InterruptedException ie) { // Bye bye log.info("Bye bye!"); } catch (Throwable e) { e.printStackTrace(); failed.set(true); } } }); } final SploutConfiguration config = SploutConfiguration.getTestConfig(); final int iterationsToPerform = config.getInt(QNodeProperties.VERSIONS_PER_TABLESPACE) + 5; for (int i = 0; i < iterationsToPerform; i++) { iteration.incrementAndGet(); log.info("Deploy iteration: " + iteration.get()); deployIteration(iteration.get(), random, client, testTablespace); new TestUtils.NotWaitingForeverCondition() { @Override public boolean endCondition() { synchronized (iterationsSeen) { return iterationsSeen.size() == (iteration.get() + 1); } } }.waitAtMost(5000); } assertEquals(false, failed.get()); service.shutdownNow(); // will interrupt all threads while (!service.isTerminated()) { Thread.sleep(100); } CoordinationStructures coord = TestUtils.getCoordinationStructures(config); assertNotNull(coord.getCopyVersionsBeingServed().get(TABLESPACE)); // Assert that there is only MAX_VERSIONS versions of the tablespace (due to old version cleanup) new TestUtils.NotWaitingForeverCondition() { @Override public boolean endCondition() { QNodeHandler handler = (QNodeHandler) qNodes.get(0).getHandler(); int seenVersions = 0; for (Map.Entry<TablespaceVersion, Tablespace> tablespaceVersion : handler.getContext() .getTablespaceVersionsMap().entrySet()) { if (tablespaceVersion.getKey().getTablespace().equals(TABLESPACE)) { seenVersions++; } } return seenVersions <= config.getInt(QNodeProperties.VERSIONS_PER_TABLESPACE); } }.waitAtMost(5000); } finally { closeSploutEnsemble(); FileUtils.deleteDirectory(new File(TMP_FOLDER)); } }
From source file:com.alibaba.wasp.jdbc.TestAtomicOperation.java
/** * Test multi-threaded row mutations.//from w w w. jav a 2s . co m */ @Test public void testRowMutationMultiThreads() throws IOException { LOG.info("Starting test testRowMutationMultiThreads"); // create 100 threads, each will alternate between adding and // removing a column int numThreads = 10; int opsPerThread = 50; AtomicOperation[] all = new AtomicOperation[numThreads]; AtomicInteger failures = new AtomicInteger(0); // create all threads for (int i = 0; i < numThreads; i++) { try { all[i] = new AtomicOperation(entityGroup, opsPerThread, conn, failures) { @Override public void run() { for (int i = 0; i < numOps; i++) { try { int lines = stmt.executeUpdate("insert into " + TABLE_NAME + " (column1,column2,column3) values(1,1,'wasptest')"); if (lines != 1) { LOG.debug(r); failures.incrementAndGet(); fail(); } } catch (SQLException e) { failures.incrementAndGet(); } } } }; } catch (SQLException e) { } } // run all threads for (int i = 0; i < numThreads; i++) { all[i].start(); } // wait for all threads to finish for (int i = 0; i < numThreads; i++) { try { all[i].join(); } catch (InterruptedException e) { } } System.out.println(failures.get()); assertEquals(opsPerThread * numThreads - 1, failures.get()); }
From source file:net.nfpj.webcounter.dm.MemCounterDM.java
@Override public Counter create(String name) throws DuplicatedCounterException { if (name == null || name.isEmpty()) { throw new NullPointerException("Name cannot be null"); }/* w w w . ja v a 2 s . c o m*/ if (counters.putIfAbsent(name, new AtomicInteger(0)) == null) { return new Counter(name, 0); } else { throw new DuplicatedCounterException(name, "Counter with name " + name + " already exists"); } }
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 w ww .j ava2 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:org.zodiark.service.action.ActionServiceImpl.java
/** * {@inheritDoc}/* www. jav a 2 s. c o m*/ */ public void actionStarted(Envelope e) { try { final PublisherResults results = mapper.readValue(e.getMessage().getData(), PublisherResults.class); eventBus.message(RETRIEVE_PUBLISHER, results.getUuid(), new Reply<PublisherEndpoint, String>() { @Override public void ok(final PublisherEndpoint p) { final AtomicInteger time = new AtomicInteger(p.action().time()); final AtmosphereResource publisher = p.resource(); final AtmosphereResource subscriber = p.action().subscriber().resource(); final Future<?> timerFuture = timer.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (time.get() == 0) return; Message m = new Message(); m.setPath(ACTION_TIMER); try { m.setData(mapper.writeValueAsString(time.getAndDecrement())); Envelope e = Envelope.newPublisherMessage(p.uuid(), m); String w = mapper.writeValueAsString(e); publisher.write(w); e = Envelope.newSubscriberMessage(p.uuid(), m); w = mapper.writeValueAsString(e); subscriber.write(w); } catch (JsonProcessingException e1) { logger.error("", e1); } } }, 1, 1, TimeUnit.SECONDS); timer.schedule(new Runnable() { @Override public void run() { timerFuture.cancel(false); Message m = new Message(); m.setPath(ACTION_COMPLETED); try { m.setData(mapper.writeValueAsString(new PublisherResults("OK"))); Envelope e = Envelope.newPublisherMessage(p.uuid(), m); String w = mapper.writeValueAsString(e); publisher.write(w); m.setData(mapper.writeValueAsString(new SubscriberResults("OK"))); e = Envelope.newSubscriberMessage(p.uuid(), m); w = mapper.writeValueAsString(e); subscriber.write(w); } catch (JsonProcessingException e1) { logger.error("", e1); } finally { eventBus.message(STREAMING_COMPLETE_ACTION, p); } } }, p.action().time(), TimeUnit.SECONDS); } @Override public void fail(ReplyException replyException) { logger.error("Unable to retrieve Publishere for {}", results.getUuid()); } }); } catch (IOException e1) { logger.error("", e1); } }
From source file:li.barter.fragments.AbstractBarterLiFragment.java
@Override public void onAttach(final Activity activity) { super.onAttach(activity); mIsAttached = true;/*from w w w . j a va 2 s. c om*/ final RequestQueue requestQueue = ((IVolleyHelper) activity.getApplication()).getRequestQueue(); mVolleyCallbacks = new VolleyCallbacks(requestQueue, this); mRequestCounter = new AtomicInteger(0); }
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();/* w w w. ja v a2s . 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(); }
From source file:org.jtheque.file.FileServiceTest.java
@Test @DirtiesContext//from www . j av a2 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()); }