List of usage examples for java.util.concurrent.atomic AtomicInteger addAndGet
public final int addAndGet(int delta)
From source file:com.adobe.acs.commons.mcp.impl.processes.renovator.Renovator.java
protected void identifyReferences(ActionManager manager) { AtomicInteger discoveredReferences = new AtomicInteger(); manager.deferredWithResolver(rr -> { moves.forEach(node -> {/* w w w .jav a 2 s . c o m*/ manager.deferredWithResolver(rr2 -> { node.visit(childNode -> { if (childNode.isSupposedToBeReferenced()) { manager.deferredWithResolver(rr3 -> { Actions.setCurrentItem("Looking for references to " + childNode.getSourcePath()); findReferences(rr3, childNode); discoveredReferences.addAndGet(childNode.getAllReferences().size()); if (detailedReport) { note(childNode.getSourcePath(), Report.all_references, childNode.getAllReferences().size()); note(childNode.getSourcePath(), Report.published_references, childNode.getPublishedReferences().size()); } }); } }); }); }); }); manager.onFinish(() -> { note("All discovered references", Report.misc, "Discovered " + discoveredReferences.get() + " references."); }); }
From source file:com.smartitengineering.cms.spi.impl.content.PythonGeneratorTest.java
@Test public void testMultiPythonRepGeneration() throws IOException { TypeRepresentationGenerator generator = new PythonRepresentationGenerator(); final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class); WorkspaceAPIImpl impl = new WorkspaceAPIImpl() { @Override// w ww . ja v a2s . co m public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) { return template; } }; impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.PYTHON, generator)); final RepresentationProvider provider = new RepresentationProviderImpl(); final WorkspaceAPI api = impl; registerBeanFactory(api); final Content content = mockery.mock(Content.class); final Field field = mockery.mock(Field.class); final FieldValue value = mockery.mock(FieldValue.class); final Map<String, Field> fieldMap = mockery.mock(Map.class); final ContentType type = mockery.mock(ContentType.class); final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap"); final RepresentationDef def = mockery.mock(RepresentationDef.class); final int threadCount = new Random().nextInt(50) + 50; logger.info("Number of parallel threads " + threadCount); final Set<Integer> expecteds = new LinkedHashSet<Integer>(); mockery.checking(new Expectations() { { exactly(threadCount).of(template).getTemplateType(); will(returnValue(TemplateType.PYTHON)); exactly(threadCount).of(template).getTemplate(); final byte[] toByteArray = IOUtils.toByteArray(getClass().getClassLoader() .getResourceAsStream("scripts/python/test-multi-rep-gen-script.py")); will(returnValue(toByteArray)); exactly(threadCount).of(template).getName(); will(returnValue(REP_NAME)); for (int i = 0; i < threadCount; ++i) { exactly(1).of(value).getValue(); will(returnValue(String.valueOf(i))); expecteds.add(i); } exactly(threadCount).of(field).getValue(); will(returnValue(value)); exactly(threadCount).of(fieldMap).get(with(Expectations.<String>anything())); will(returnValue(field)); exactly(threadCount).of(content).getFields(); will(returnValue(fieldMap)); exactly(threadCount).of(content).getContentDefinition(); will(returnValue(type)); final ContentId contentId = mockery.mock(ContentId.class); exactly(2 * threadCount).of(content).getContentId(); will(returnValue(contentId)); final WorkspaceId wId = mockery.mock(WorkspaceId.class); exactly(threadCount).of(contentId).getWorkspaceId(); will(returnValue(wId)); exactly(2 * threadCount).of(type).getRepresentationDefs(); will(returnValue(reps)); exactly(2 * threadCount).of(reps).get(with(REP_NAME)); will(returnValue(def)); exactly(threadCount).of(def).getParameters(); will(returnValue(Collections.emptyMap())); exactly(threadCount).of(def).getMIMEType(); will(returnValue(GroovyGeneratorTest.MIME_TYPE)); final ResourceUri rUri = mockery.mock(ResourceUri.class); exactly(threadCount).of(def).getResourceUri(); will(returnValue(rUri)); exactly(threadCount).of(rUri).getValue(); will(returnValue("iUri")); } }); final Set<String> set = Collections.synchronizedSet(new LinkedHashSet<String>(threadCount)); final List<String> list = Collections.synchronizedList(new ArrayList<String>(threadCount)); final AtomicInteger integer = new AtomicInteger(0); Threads group = new Threads(); for (int i = 0; i < threadCount; ++i) { group.addThread(new Thread(new Runnable() { public void run() { Representation representation = provider.getRepresentation(REP_NAME, type, content); Assert.assertNotNull(representation); Assert.assertEquals(REP_NAME, representation.getName()); final String rep = StringUtils.newStringUtf8(representation.getRepresentation()); list.add(rep); set.add(rep); Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType()); integer.addAndGet(1); } })); } long start = System.currentTimeMillis(); group.start(); try { group.join(); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } long end = System.currentTimeMillis(); logger.info("For generating " + threadCount + " simple representation it took " + (end - start) + "ms"); logger.info("Generated reps list: " + list); logger.info("Generated reps set: " + set); Assert.assertEquals(threadCount, expecteds.size()); Assert.assertEquals(threadCount, integer.get()); Assert.assertEquals(threadCount, list.size()); Assert.assertEquals(threadCount, set.size()); }
From source file:com.smartitengineering.cms.spi.impl.content.VelocityGeneratorTest.java
@Test public void testMultiVelocityRepGeneration() throws IOException { TypeRepresentationGenerator generator = new VelocityRepresentationGenerator(); final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class); WorkspaceAPIImpl impl = new WorkspaceAPIImpl() { @Override/*w w w . j a v a 2 s. c o m*/ public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) { return template; } }; impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.VELOCITY, generator)); final RepresentationProvider provider = new RepresentationProviderImpl(); final WorkspaceAPI api = impl; registerBeanFactory(api); final Content content = mockery.mock(Content.class); final Field field = mockery.mock(Field.class); final FieldValue value = mockery.mock(FieldValue.class); final Map<String, Field> fieldMap = mockery.mock(Map.class); final ContentType type = mockery.mock(ContentType.class); final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap"); final RepresentationDef def = mockery.mock(RepresentationDef.class); final int threadCount = new Random().nextInt(100); logger.info("Number of parallel threads " + threadCount); mockery.checking(new Expectations() { { exactly(threadCount).of(template).getTemplateType(); will(returnValue(TemplateType.VELOCITY)); exactly(threadCount).of(template).getTemplate(); final byte[] toByteArray = IOUtils.toByteArray( getClass().getClassLoader().getResourceAsStream("scripts/velocity/test-template.vm")); will(returnValue(toByteArray)); exactly(threadCount).of(template).getName(); will(returnValue(REP_NAME)); for (int i = 0; i < threadCount; ++i) { exactly(1).of(value).getValue(); will(returnValue(String.valueOf(i))); } exactly(threadCount).of(field).getValue(); will(returnValue(value)); exactly(threadCount).of(fieldMap).get(with(Expectations.<String>anything())); will(returnValue(field)); exactly(threadCount).of(content).getFields(); will(returnValue(fieldMap)); exactly(threadCount).of(content).getContentDefinition(); will(returnValue(type)); final ContentId contentId = mockery.mock(ContentId.class); exactly(2 * threadCount).of(content).getContentId(); will(returnValue(contentId)); final WorkspaceId wId = mockery.mock(WorkspaceId.class); exactly(threadCount).of(contentId).getWorkspaceId(); will(returnValue(wId)); exactly(2 * threadCount).of(type).getRepresentationDefs(); will(returnValue(reps)); exactly(2 * threadCount).of(reps).get(with(REP_NAME)); will(returnValue(def)); exactly(threadCount).of(def).getParameters(); will(returnValue(Collections.emptyMap())); exactly(threadCount).of(def).getMIMEType(); will(returnValue(GroovyGeneratorTest.MIME_TYPE)); final ResourceUri rUri = mockery.mock(ResourceUri.class); exactly(threadCount).of(def).getResourceUri(); will(returnValue(rUri)); exactly(threadCount).of(rUri).getValue(); will(returnValue("iUri")); } }); final Set<String> set = Collections.synchronizedSet(new LinkedHashSet<String>(threadCount)); final List<String> list = Collections.synchronizedList(new ArrayList<String>(threadCount)); final AtomicInteger integer = new AtomicInteger(0); Threads group = new Threads(); for (int i = 0; i < threadCount; ++i) { group.addThread(new Thread(new Runnable() { public void run() { Representation representation = provider.getRepresentation(REP_NAME, type, content); Assert.assertNotNull(representation); Assert.assertEquals(REP_NAME, representation.getName()); final String rep = StringUtils.newStringUtf8(representation.getRepresentation()); list.add(rep); set.add(rep); Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType()); integer.addAndGet(1); } })); } group.start(); try { group.join(); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } logger.info("Generated reps list: " + list); logger.info("Generated reps set: " + set); Assert.assertEquals(threadCount, integer.get()); Assert.assertEquals(threadCount, list.size()); Assert.assertEquals(threadCount, set.size()); }
From source file:com.smartitengineering.cms.spi.impl.content.VelocityGeneratorTest.java
@Test public void testContinuousVelocityRepGeneration() throws IOException { TypeRepresentationGenerator generator = new VelocityRepresentationGenerator(); final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class); WorkspaceAPIImpl impl = new WorkspaceAPIImpl() { @Override/*from ww w .j a v a 2s . c o m*/ public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) { return template; } }; impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.VELOCITY, generator)); final RepresentationProvider provider = new RepresentationProviderImpl(); final WorkspaceAPI api = impl; registerBeanFactory(api); final Content content = mockery.mock(Content.class); final Field field = mockery.mock(Field.class); final FieldValue value = mockery.mock(FieldValue.class); final Map<String, Field> fieldMap = mockery.mock(Map.class); final ContentType type = mockery.mock(ContentType.class); final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap"); final RepresentationDef def = mockery.mock(RepresentationDef.class); final int threadCount = new Random().nextInt(100); logger.info("Number of parallel threads " + threadCount); mockery.checking(new Expectations() { { exactly(threadCount).of(template).getTemplateType(); will(returnValue(TemplateType.VELOCITY)); exactly(threadCount).of(template).getTemplate(); final byte[] toByteArray = IOUtils.toByteArray( getClass().getClassLoader().getResourceAsStream("scripts/velocity/test-template.vm")); will(returnValue(toByteArray)); exactly(threadCount).of(template).getName(); will(returnValue(REP_NAME)); for (int i = 0; i < threadCount; ++i) { exactly(1).of(value).getValue(); will(returnValue(String.valueOf(Integer.MAX_VALUE))); } exactly(threadCount).of(field).getValue(); will(returnValue(value)); exactly(threadCount).of(fieldMap).get(with(Expectations.<String>anything())); will(returnValue(field)); exactly(threadCount).of(content).getFields(); will(returnValue(fieldMap)); exactly(threadCount).of(content).getContentDefinition(); will(returnValue(type)); final ContentId contentId = mockery.mock(ContentId.class); exactly(2 * threadCount).of(content).getContentId(); will(returnValue(contentId)); final WorkspaceId wId = mockery.mock(WorkspaceId.class); exactly(threadCount).of(contentId).getWorkspaceId(); will(returnValue(wId)); exactly(2 * threadCount).of(type).getRepresentationDefs(); will(returnValue(reps)); exactly(2 * threadCount).of(reps).get(with(REP_NAME)); will(returnValue(def)); exactly(threadCount).of(def).getParameters(); will(returnValue(Collections.emptyMap())); exactly(threadCount).of(def).getMIMEType(); will(returnValue(GroovyGeneratorTest.MIME_TYPE)); final ResourceUri rUri = mockery.mock(ResourceUri.class); exactly(threadCount).of(def).getResourceUri(); will(returnValue(rUri)); exactly(threadCount).of(rUri).getValue(); will(returnValue("iUri")); } }); final Set<String> set = Collections.synchronizedSet(new LinkedHashSet<String>(threadCount)); final List<String> list = Collections.synchronizedList(new ArrayList<String>(threadCount)); final AtomicInteger integer = new AtomicInteger(0); Threads group = new Threads(); for (int i = 0; i < threadCount; ++i) { group.addThread(new Thread(new Runnable() { public void run() { Representation representation = provider.getRepresentation(REP_NAME, type, content); Assert.assertNotNull(representation); Assert.assertEquals(REP_NAME, representation.getName()); final String rep = StringUtils.newStringUtf8(representation.getRepresentation()); list.add(rep); set.add(rep); Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType()); integer.addAndGet(1); } })); } group.start(); try { group.join(); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } logger.info("Generated reps list: " + list); logger.info("Generated reps set: " + set); Assert.assertEquals(threadCount, integer.get()); Assert.assertEquals(threadCount, list.size()); Assert.assertEquals(1, set.size()); }
From source file:org.apache.hadoop.hbase.tool.TestLoadIncrementalHFilesSplitRecovery.java
/** * This test splits a table and attempts to bulk load. The bulk import files should be split * before atomically importing./*from w w w.j a v a2 s.co m*/ */ @Test(timeout = 120000) public void testGroupOrSplitPresplit() throws Exception { final TableName table = TableName.valueOf(name.getMethodName()); try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) { setupTable(connection, table, 10); populateTable(connection, table, 1); assertExpectedTable(connection, table, ROWCOUNT, 1); forceSplit(table); final AtomicInteger countedLqis = new AtomicInteger(); LoadIncrementalHFiles lih = new LoadIncrementalHFiles(util.getConfiguration()) { @Override protected Pair<List<LoadQueueItem>, String> groupOrSplit( Multimap<ByteBuffer, LoadQueueItem> regionGroups, final LoadQueueItem item, final Table htable, final Pair<byte[][], byte[][]> startEndKeys) throws IOException { Pair<List<LoadQueueItem>, String> lqis = super.groupOrSplit(regionGroups, item, htable, startEndKeys); if (lqis != null && lqis.getFirst() != null) { countedLqis.addAndGet(lqis.getFirst().size()); } return lqis; } }; // create HFiles for different column families Path bulk = buildBulkFiles(table, 2); try (Table t = connection.getTable(table); RegionLocator locator = connection.getRegionLocator(table); Admin admin = connection.getAdmin()) { lih.doBulkLoad(bulk, admin, t, locator); } assertExpectedTable(connection, table, ROWCOUNT, 2); assertEquals(20, countedLqis.get()); } }
From source file:org.apache.hadoop.hbase.tool.TestLoadIncrementalHFilesSplitRecovery.java
@Test(timeout = 120000) public void testGroupOrSplitWhenRegionHoleExistsInMeta() throws Exception { final TableName tableName = TableName.valueOf(name.getMethodName()); byte[][] SPLIT_KEYS = new byte[][] { Bytes.toBytes("row_00000100") }; // Share connection. We were failing to find the table with our new reverse scan because it // looks for first region, not any region -- that is how it works now. The below removes first // region in test. Was reliant on the Connection caching having first region. Connection connection = ConnectionFactory.createConnection(util.getConfiguration()); Table table = connection.getTable(tableName); setupTableWithSplitkeys(tableName, 10, SPLIT_KEYS); Path dir = buildBulkFiles(tableName, 2); final AtomicInteger countedLqis = new AtomicInteger(); LoadIncrementalHFiles loader = new LoadIncrementalHFiles(util.getConfiguration()) { @Override//from w w w . ja va 2 s . c o m protected Pair<List<LoadQueueItem>, String> groupOrSplit( Multimap<ByteBuffer, LoadQueueItem> regionGroups, final LoadQueueItem item, final Table htable, final Pair<byte[][], byte[][]> startEndKeys) throws IOException { Pair<List<LoadQueueItem>, String> lqis = super.groupOrSplit(regionGroups, item, htable, startEndKeys); if (lqis != null && lqis.getFirst() != null) { countedLqis.addAndGet(lqis.getFirst().size()); } return lqis; } }; // do bulkload when there is no region hole in hbase:meta. try (Table t = connection.getTable(tableName); RegionLocator locator = connection.getRegionLocator(tableName); Admin admin = connection.getAdmin()) { loader.doBulkLoad(dir, admin, t, locator); } catch (Exception e) { LOG.error("exeception=", e); } // check if all the data are loaded into the table. this.assertExpectedTable(tableName, ROWCOUNT, 2); dir = buildBulkFiles(tableName, 3); // Mess it up by leaving a hole in the hbase:meta List<RegionInfo> regionInfos = MetaTableAccessor.getTableRegions(connection, tableName); for (RegionInfo regionInfo : regionInfos) { if (Bytes.equals(regionInfo.getStartKey(), HConstants.EMPTY_BYTE_ARRAY)) { MetaTableAccessor.deleteRegion(connection, regionInfo); break; } } try (Table t = connection.getTable(tableName); RegionLocator locator = connection.getRegionLocator(tableName); Admin admin = connection.getAdmin()) { loader.doBulkLoad(dir, admin, t, locator); } catch (Exception e) { LOG.error("exception=", e); assertTrue("IOException expected", e instanceof IOException); } table.close(); // Make sure at least the one region that still exists can be found. regionInfos = MetaTableAccessor.getTableRegions(connection, tableName); assertTrue(regionInfos.size() >= 1); this.assertExpectedTable(connection, tableName, ROWCOUNT, 2); connection.close(); }
From source file:com.indeed.lsmtree.recordcache.PersistentRecordCache.java
/** * Performs lookup for multiple keys and returns a streaming iterator to results. * Each element in the iterator is one of * (1) an exception associated with a single lookup * (2) a key value tuple/* w w w . j av a 2 s . c o m*/ * * @param keys lookup keys * @param progress (optional) an AtomicInteger for tracking progress * @param skipped (optional) an AtomicInteger for tracking missing keys * @return iterator of lookup results */ public Iterator<Either<Exception, P2<K, V>>> getStreaming(final @Nonnull Iterator<K> keys, final @Nullable AtomicInteger progress, final @Nullable AtomicInteger skipped) { log.info("starting store lookups"); LongArrayList addressList = new LongArrayList(); int notFound = 0; while (keys.hasNext()) { final K key = keys.next(); final Long address; try { address = index.get(key); } catch (IOException e) { log.error("error", e); return Iterators.singletonIterator(Left.<Exception, P2<K, V>>of(new IndexReadException(e))); } if (address != null) { addressList.add(address); } else { notFound++; } } if (progress != null) progress.addAndGet(notFound); if (skipped != null) skipped.addAndGet(notFound); log.info("store lookups complete, sorting addresses"); final long[] addresses = addressList.elements(); Arrays.sort(addresses, 0, addressList.size()); log.info("initializing store lookup iterator"); final BlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<Runnable>(100); final Iterator<List<Long>> iterable = Iterators.partition(addressList.iterator(), 1000); final ExecutorService primerThreads = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, taskQueue, new NamedThreadFactory("store priming thread", true, log), new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { taskQueue.put(r); } catch (InterruptedException e) { log.error("error", e); throw new RuntimeException(e); } } }); final BlockingQueue<List<Either<Exception, P2<K, V>>>> completionQueue = new ArrayBlockingQueue<List<Either<Exception, P2<K, V>>>>( 10); final AtomicLong runningTasks = new AtomicLong(0); final AtomicBoolean taskSubmitterRunning = new AtomicBoolean(true); new Thread(new Runnable() { @Override public void run() { while (iterable.hasNext()) { runningTasks.incrementAndGet(); final List<Long> addressesSublist = iterable.next(); primerThreads.submit(new FutureTask<List<Either<Exception, P2<K, V>>>>( new RecordLookupTask(addressesSublist)) { @Override protected void done() { try { final List<Either<Exception, P2<K, V>>> results = get(); if (progress != null) { progress.addAndGet(results.size()); } completionQueue.put(results); } catch (InterruptedException e) { log.error("error", e); throw new RuntimeException(e); } catch (ExecutionException e) { log.error("error", e); throw new RuntimeException(e); } } }); } taskSubmitterRunning.set(false); } }, "RecordLookupTaskSubmitterThread").start(); return new Iterator<Either<Exception, P2<K, V>>>() { Iterator<Either<Exception, P2<K, V>>> currentIterator; @Override public boolean hasNext() { if (currentIterator != null && currentIterator.hasNext()) return true; while (taskSubmitterRunning.get() || runningTasks.get() > 0) { try { final List<Either<Exception, P2<K, V>>> list = completionQueue.poll(1, TimeUnit.SECONDS); if (list != null) { log.debug("remaining: " + runningTasks.decrementAndGet()); currentIterator = list.iterator(); if (currentIterator.hasNext()) return true; } } catch (InterruptedException e) { log.error("error", e); throw new RuntimeException(e); } } primerThreads.shutdown(); return false; } @Override public Either<Exception, P2<K, V>> next() { return currentIterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
From source file:com.adobe.acs.commons.mcp.impl.processes.renovator.Renovator.java
private void buildMoveTree(Resource r, int level, MovingNode root, AtomicInteger visitedSourceNodes) throws RepositoryException { if (level > 0) { Actions.setCurrentItem(r.getPath()); Optional<MovingNode> node = buildMoveNode(r); if (node.isPresent()) { MovingNode childNode = node.get(); String parentPath = StringUtils.substringBeforeLast(r.getPath(), "/"); MovingNode parent = root.findByPath(parentPath).orElseThrow( () -> new RepositoryException("Unable to find data structure for node " + parentPath)); parent.addChild(childNode);// w ww. j a v a2 s . c om if (detailedReport) { note(childNode.getSourcePath(), Report.target, childNode.getDestinationPath()); } visitedSourceNodes.addAndGet(1); } } }
From source file:reactor.io.net.tcp.SmokeTests.java
@SuppressWarnings("unchecked") private int getClientDataSize(int threadCount, final Sender sender, int count) throws Exception { final CountDownLatch latch = new CountDownLatch(1); windowsData.clear();// w ww.jav a 2s . c o m Thread.sleep(1500); Runnable srunner = new Runnable() { public void run() { try { sender.sendNext(count); } catch (Exception ie) { ie.printStackTrace(); } } }; Thread st = new Thread(srunner, "SenderThread"); st.start(); CountDownLatch thread = new CountDownLatch(threadCount); AtomicInteger counter = new AtomicInteger(); for (int i = 0; i < threadCount; ++i) { Runnable runner = new Runnable() { public void run() { try { boolean empty = false; while (true) { List<String> res = getClientDataPromise(); if (res == null) { if (empty) break; empty = true; continue; } List<Integer> collected = parseCollection(res); Collections.sort(collected); int size = collected.size(); //previous empty if (size == 0 && empty) break; counter.addAndGet(size); empty = size == 0; System.out.println("Client received " + size + " elements, current total: " + counter + ", batches: " + integerPostConcat + ", between [ " + (size > 0 ? collected.get(0) + " -> " + collected.get(size - 1) : "") + " ]"); } System.out.println("Client finished"); } catch (Exception ie) { ie.printStackTrace(); } finally { thread.countDown(); } } }; Thread t = new Thread(runner, "SmokeThread" + i); t.start(); } latch.countDown(); thread.await(500, TimeUnit.SECONDS); return counter.get(); }
From source file:reactor.io.net.tcp.SmokeTests.java
@SuppressWarnings("unchecked") private List<Integer> getClientDatas(int threadCount, final Sender sender, int count) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final List<Integer> datas = SynchronizedList.decorate(new ArrayList<>()); windowsData.clear();//from w w w . jav a2 s . com Thread.sleep(1500); Runnable srunner = new Runnable() { public void run() { try { sender.sendNext(count); } catch (Exception ie) { ie.printStackTrace(); } } }; Thread st = new Thread(srunner, "SenderThread"); st.start(); CountDownLatch thread = new CountDownLatch(threadCount); AtomicInteger counter = new AtomicInteger(); for (int i = 0; i < threadCount; ++i) { Runnable runner = new Runnable() { public void run() { try { boolean empty = false; while (true) { List<String> res = getClientDataPromise(); if (res == null) { if (empty) break; empty = true; continue; } List<Integer> collected = parseCollection(res); Collections.sort(collected); int size = collected.size(); //previous empty if (size == 0 && empty) break; datas.addAll(collected); counter.addAndGet(size); empty = size == 0; System.out.println("Client received " + size + " elements, current total: " + counter + ", batches: " + integerPostConcat + ", between [ " + (size > 0 ? collected.get(0) + " -> " + collected.get(size - 1) : "") + " ]"); } System.out.println("Client finished"); } catch (Exception ie) { ie.printStackTrace(); } finally { thread.countDown(); } } }; Thread t = new Thread(runner, "SmokeThread" + i); t.start(); } latch.countDown(); thread.await(500, TimeUnit.SECONDS); return datas; }