List of usage examples for java.util.concurrent.atomic AtomicInteger get
public final int get()
From source file:org.zenoss.zep.dao.impl.DaoUtilsTest.java
@Test public void testDeadlockRetryNestedException() throws Exception { final AtomicInteger i = new AtomicInteger(); final int returnVal = new Random().nextInt(); int result = DaoUtils.deadlockRetry(new Callable<Integer>() { @Override/* w ww . ja va 2s . c om*/ public Integer call() throws Exception { if (i.incrementAndGet() < 5) { throw new RuntimeException(new DeadlockLoserDataAccessException("My fake exception", null)); } return returnVal; } }); assertEquals(i.get(), 5); assertEquals(result, returnVal); }
From source file:io.pravega.client.state.impl.SynchronizerTest.java
@Test(timeout = 20000) public void testCompaction() throws EndOfSegmentException { String streamName = "streamName"; String scope = "scope"; MockSegmentStreamFactory ioFactory = new MockSegmentStreamFactory(); @Cleanup//w ww. ja va2 s . c o m MockClientFactory clientFactory = new MockClientFactory(scope, ioFactory); StateSynchronizer<RevisionedImpl> sync = clientFactory.createStateSynchronizer(streamName, new JavaSerializer<>(), new JavaSerializer<>(), SynchronizerConfig.builder().build()); AtomicInteger callCount = new AtomicInteger(0); sync.initialize(new RegularUpdate()); sync.updateState(state -> { callCount.incrementAndGet(); return Collections.singletonList(new RegularUpdate()); }); assertEquals(1, callCount.get()); sync.updateState(state -> { callCount.incrementAndGet(); return Collections.singletonList(new RegularUpdate()); }); assertEquals(2, callCount.get()); sync.compact(state -> { callCount.incrementAndGet(); return new RegularUpdate(); }); assertEquals(3, callCount.get()); sync.updateState(s -> { callCount.incrementAndGet(); return Collections.singletonList(new RegularUpdate()); }); assertEquals(5, callCount.get()); sync.compact(state -> { callCount.incrementAndGet(); return new RegularUpdate(); }); assertEquals(6, callCount.get()); }
From source file:org.jtheque.features.FeatureServiceTest.java
@Test public void listenerCalledForAddingFeature() { final AtomicInteger addCounter = new AtomicInteger(0); final AtomicInteger removeCounter = new AtomicInteger(0); final AtomicInteger modifyCounter = new AtomicInteger(0); featureService.addFeatureListener(new MyFeatureListener(addCounter, removeCounter, modifyCounter)); featureService.addMenu("no-module", new MenuNoMain()); assertEquals(0, addCounter.get()); assertEquals(0, removeCounter.get()); assertEquals(1, modifyCounter.get()); featureService.addMenu("no-module", new MenuNoMain()); assertEquals(0, addCounter.get());//w w w.j a v a 2 s. c o m assertEquals(0, removeCounter.get()); assertEquals(2, modifyCounter.get()); }
From source file:org.glassfish.jersey.examples.sseitemstore.jaxrs.JaxrsItemStoreResourceTest.java
/** * Test the item addition, addition event broadcasting and item retrieval from {@link JaxrsItemStoreResource}. * * @throws Exception in case of a test failure. *///from w ww .ja v a 2s .c o m @Test public void testItemsStore() throws Exception { final List<String> items = Collections.unmodifiableList(Arrays.asList("foo", "bar", "baz")); final WebTarget itemsTarget = target("items"); final CountDownLatch latch = new CountDownLatch(items.size() * MAX_LISTENERS * 2); // countdown on all events final List<Queue<Integer>> indexQueues = new ArrayList<>(MAX_LISTENERS); final SseEventSource[] sources = new SseEventSource[MAX_LISTENERS]; final AtomicInteger sizeEventsCount = new AtomicInteger(0); for (int i = 0; i < MAX_LISTENERS; i++) { final int id = i; final SseEventSource es = SseEventSource.target(itemsTarget.path("events")).build(); sources[id] = es; final Queue<Integer> indexes = new ConcurrentLinkedQueue<>(); indexQueues.add(indexes); es.register(inboundEvent -> { try { if (null == inboundEvent.getName()) { final String data = inboundEvent.readData(); LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId() + " data=" + data); indexes.add(items.indexOf(data)); } else if ("size".equals(inboundEvent.getName())) { sizeEventsCount.incrementAndGet(); } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex); indexes.add(-999); } finally { latch.countDown(); } }); } try { open(sources); items.forEach((item) -> postItem(itemsTarget, item)); assertTrue("Waiting to receive all events has timed out.", latch.await((1000 + MAX_LISTENERS * RECONNECT_DEFAULT) * getAsyncTimeoutMultiplier(), TimeUnit.MILLISECONDS)); // need to force disconnect on server in order for EventSource.close(...) to succeed with HttpUrlConnection sendCommand(itemsTarget, "disconnect"); } finally { close(sources); } String postedItems = itemsTarget.request().get(String.class); items.forEach( (item) -> assertTrue("Item '" + item + "' not stored on server.", postedItems.contains(item))); final AtomicInteger queueId = new AtomicInteger(0); indexQueues.forEach((indexes) -> { for (int i = 0; i < items.size(); i++) { assertTrue("Event for '" + items.get(i) + "' not received in queue " + queueId.get(), indexes.contains(i)); } assertEquals("Not received the expected number of events in queue " + queueId.get(), items.size(), indexes.size()); queueId.incrementAndGet(); }); assertEquals("Number of received 'size' events does not match.", items.size() * MAX_LISTENERS, sizeEventsCount.get()); }
From source file:org.apache.hadoop.hbase.executor.TestExecutorService.java
@Test public void testExecutorService() throws Exception { int maxThreads = 5; int maxTries = 10; int sleepInterval = 10; Server mockedServer = mock(Server.class); when(mockedServer.getConfiguration()).thenReturn(HBaseConfiguration.create()); // Start an executor service pool with max 5 threads ExecutorService executorService = new ExecutorService("unit_test"); executorService.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS, maxThreads); Executor executor = executorService.getExecutor(ExecutorType.MASTER_SERVER_OPERATIONS); ThreadPoolExecutor pool = executor.threadPoolExecutor; // Assert no threads yet assertEquals(0, pool.getPoolSize()); AtomicBoolean lock = new AtomicBoolean(true); AtomicInteger counter = new AtomicInteger(0); // Submit maxThreads executors. for (int i = 0; i < maxThreads; i++) { executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); }/*from w w w . j av a 2 s .c o m*/ // The TestEventHandler will increment counter when it starts. int tries = 0; while (counter.get() < maxThreads && tries < maxTries) { LOG.info("Waiting for all event handlers to start..."); Thread.sleep(sleepInterval); tries++; } // Assert that pool is at max threads. assertEquals(maxThreads, counter.get()); assertEquals(maxThreads, pool.getPoolSize()); ExecutorStatus status = executor.getStatus(); assertTrue(status.queuedEvents.isEmpty()); assertEquals(5, status.running.size()); checkStatusDump(status); // Now interrupt the running Executor synchronized (lock) { lock.set(false); lock.notifyAll(); } // Executor increments counter again on way out so.... test that happened. while (counter.get() < (maxThreads * 2) && tries < maxTries) { System.out.println("Waiting for all event handlers to finish..."); Thread.sleep(sleepInterval); tries++; } assertEquals(maxThreads * 2, counter.get()); assertEquals(maxThreads, pool.getPoolSize()); // Add more than the number of threads items. // Make sure we don't get RejectedExecutionException. for (int i = 0; i < (2 * maxThreads); i++) { executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); } // Now interrupt the running Executor synchronized (lock) { lock.set(false); lock.notifyAll(); } // Make sure threads are still around even after their timetolive expires. Thread.sleep(ExecutorService.Executor.keepAliveTimeInMillis * 2); assertEquals(maxThreads, pool.getPoolSize()); executorService.shutdown(); assertEquals(0, executorService.getAllExecutorStatuses().size()); // Test that submit doesn't throw NPEs executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); }
From source file:com.alibaba.wasp.executor.TestExecutorService.java
@Test public void testExecutorService() throws Exception { int maxThreads = 5; int maxTries = 10; int sleepInterval = 10; Server mockedServer = mock(Server.class); when(mockedServer.getConfiguration()).thenReturn(conf); // Start an executor service pool with max 5 threads ExecutorService executorService = new ExecutorService("unit_test"); executorService.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS, maxThreads); Executor executor = executorService.getExecutor(ExecutorType.MASTER_SERVER_OPERATIONS); ThreadPoolExecutor pool = executor.threadPoolExecutor; // Assert no threads yet assertEquals(0, pool.getPoolSize()); AtomicBoolean lock = new AtomicBoolean(true); AtomicInteger counter = new AtomicInteger(0); // Submit maxThreads executors. for (int i = 0; i < maxThreads; i++) { executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); }// w w w . ja va 2 s .c o m // The TestEventHandler will increment counter when it starts. int tries = 0; while (counter.get() < maxThreads && tries < maxTries) { LOG.info("Waiting for all event handlers to start..."); Thread.sleep(sleepInterval); tries++; } // Assert that pool is at max threads. assertEquals(maxThreads, counter.get()); assertEquals(maxThreads, pool.getPoolSize()); ExecutorStatus status = executor.getStatus(); assertTrue(status.queuedEvents.isEmpty()); assertEquals(5, status.running.size()); checkStatusDump(status); // Now interrupt the running Executor synchronized (lock) { lock.set(false); lock.notifyAll(); } // Executor increments counter again on way out so.... test that happened. while (counter.get() < (maxThreads * 2) && tries < maxTries) { System.out.println("Waiting for all event handlers to finish..."); Thread.sleep(sleepInterval); tries++; } assertEquals(maxThreads * 2, counter.get()); assertEquals(maxThreads, pool.getPoolSize()); // Add more than the number of threads items. // Make sure we don't get RejectedExecutionException. for (int i = 0; i < (2 * maxThreads); i++) { executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); } // Now interrupt the running Executor synchronized (lock) { lock.set(false); lock.notifyAll(); } // Make sure threads are still around even after their timetolive expires. Thread.sleep(ExecutorService.Executor.keepAliveTimeInMillis * 2); assertEquals(maxThreads, pool.getPoolSize()); executorService.shutdown(); assertEquals(0, executorService.getAllExecutorStatuses().size()); // Test that submit doesn't throw NPEs executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); }
From source file:org.apache.hadoop.hbase.procedure2.TestProcedureSchedulerConcurrency.java
private void testConcurrentWaitWake(final boolean useWakeBatch) throws Exception { final int WAIT_THRESHOLD = 2500; final int NPROCS = 20; final int NRUNS = 500; final ProcedureScheduler sched = procSched; for (long i = 0; i < NPROCS; ++i) { sched.addBack(new TestProcedureWithEvent(i)); }//from ww w.ja v a 2s. c o m final Thread[] threads = new Thread[4]; final AtomicInteger waitCount = new AtomicInteger(0); final AtomicInteger wakeCount = new AtomicInteger(0); final ConcurrentSkipListSet<TestProcedureWithEvent> waitQueue = new ConcurrentSkipListSet<TestProcedureWithEvent>(); threads[0] = new Thread() { @Override public void run() { long lastUpdate = 0; while (true) { final int oldWakeCount = wakeCount.get(); if (useWakeBatch) { ProcedureEvent[] ev = new ProcedureEvent[waitQueue.size()]; for (int i = 0; i < ev.length; ++i) { ev[i] = waitQueue.pollFirst().getEvent(); LOG.debug("WAKE BATCH " + ev[i] + " total=" + wakeCount.get()); } sched.wakeEvents(ev.length, ev); wakeCount.addAndGet(ev.length); } else { int size = waitQueue.size(); while (size-- > 0) { ProcedureEvent ev = waitQueue.pollFirst().getEvent(); sched.wakeEvent(ev); LOG.debug("WAKE " + ev + " total=" + wakeCount.get()); wakeCount.incrementAndGet(); } } if (wakeCount.get() != oldWakeCount) { lastUpdate = System.currentTimeMillis(); } else if (wakeCount.get() >= NRUNS && (System.currentTimeMillis() - lastUpdate) > WAIT_THRESHOLD) { break; } Threads.sleepWithoutInterrupt(25); } } }; for (int i = 1; i < threads.length; ++i) { threads[i] = new Thread() { @Override public void run() { while (true) { TestProcedureWithEvent proc = (TestProcedureWithEvent) sched.poll(); if (proc == null) continue; sched.suspendEvent(proc.getEvent()); waitQueue.add(proc); sched.waitEvent(proc.getEvent(), proc); LOG.debug("WAIT " + proc.getEvent()); if (waitCount.incrementAndGet() >= NRUNS) { break; } } } }; } for (int i = 0; i < threads.length; ++i) { threads[i].start(); } for (int i = 0; i < threads.length; ++i) { threads[i].join(); } sched.clear(); }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java
private void doLocking(InterProcessLock lock, AtomicInteger concurrentCount, AtomicInteger maxConcurrentCount, Random random, int maxAllowed) throws Exception { try {/*from w w w. j av a 2s . c o m*/ Assert.assertTrue(lock.acquire(10, TimeUnit.SECONDS)); int localConcurrentCount; synchronized (this) { localConcurrentCount = concurrentCount.incrementAndGet(); if (localConcurrentCount > maxConcurrentCount.get()) { maxConcurrentCount.set(localConcurrentCount); } } Assert.assertTrue(localConcurrentCount <= maxAllowed, "" + localConcurrentCount); Thread.sleep(random.nextInt(9) + 1); } finally { synchronized (this) { concurrentCount.decrementAndGet(); lock.release(); } } }
From source file:com.cloudera.oryx.app.als.FeatureVectorsTest.java
@Test public void testConcurrent() throws Exception { FeatureVectors fv = new FeatureVectors(); AtomicInteger counter = new AtomicInteger(); int numWorkers = 16; int numIterations = 10000; ExecUtils.doInParallel(numWorkers, i -> { for (int j = 0; j < numIterations; j++) { int c = counter.getAndIncrement(); fv.setVector(Integer.toString(c), new float[] { c }); }//w ww. j a v a 2 s. c om }); assertEquals((long) numIterations * numWorkers, fv.size()); assertEquals((long) numIterations * numWorkers, counter.get()); ExecUtils.doInParallel(numWorkers, i -> { for (int j = 0; j < numIterations; j++) { fv.removeVector(Integer.toString(counter.decrementAndGet())); } }); assertEquals(0, fv.size()); }
From source file:com.squarespace.template.CompilerTest.java
@Test public void testLoggingHook() throws CodeException { final AtomicInteger count = new AtomicInteger(); LoggingHook loggingHook = new LoggingHook() { @Override/*w w w . j a v a 2s . c o m*/ public void log(Exception e) { count.incrementAndGet(); assertTrue(e instanceof NullPointerException); } }; Context ctx = COMPILER.newExecutor().template("{@|npe}").json("123").safeExecution(true) .loggingHook(loggingHook).execute(); assertEquals(count.get(), 1); assertEquals(ctx.getErrors().size(), 1); assertEquals(ctx.getErrors().get(0).getType(), ExecuteErrorType.UNEXPECTED_ERROR); }