List of usage examples for java.lang Thread join
public final void join() throws InterruptedException
From source file:com.espertech.esper.regression.nwtable.TestTableMTUngroupedAccessReadMergeWrite.java
private void tryMT(int numSeconds, int numWriteThreads) throws Exception { String eplCreateVariable = "create table varagg (c0 int, c1 int, c2 int, c3 int, c4 int, c5 int)"; epService.getEPAdministrator().createEPL(eplCreateVariable); String eplMerge = "on SupportBean_S0 merge varagg " + "when not matched then insert select -1 as c0, -1 as c1, -1 as c2, -1 as c3, -1 as c4, -1 as c5 " + "when matched then update set c0=id, c1=id, c2=id, c3=id, c4=id, c5=id"; epService.getEPAdministrator().createEPL(eplMerge); SupportUpdateListener listener = new SupportUpdateListener(); String eplQuery = "select varagg.c0 as c0, varagg.c1 as c1, varagg.c2 as c2," + "varagg.c3 as c3, varagg.c4 as c4, varagg.c5 as c5 from SupportBean_S1"; epService.getEPAdministrator().createEPL(eplQuery).addListener(listener); Thread[] writeThreads = new Thread[numWriteThreads]; WriteRunnable[] writeRunnables = new WriteRunnable[numWriteThreads]; for (int i = 0; i < writeThreads.length; i++) { writeRunnables[i] = new WriteRunnable(epService, i); writeThreads[i] = new Thread(writeRunnables[i]); writeThreads[i].start();/*from w ww . j a va 2s.c o m*/ } ReadRunnable readRunnable = new ReadRunnable(epService, listener); Thread readThread = new Thread(readRunnable); readThread.start(); Thread.sleep(numSeconds * 1000); // join log.info("Waiting for completion"); for (int i = 0; i < writeThreads.length; i++) { writeRunnables[i].setShutdown(true); writeThreads[i].join(); assertNull(writeRunnables[i].getException()); } readRunnable.setShutdown(true); readThread.join(); assertNull(readRunnable.getException()); }
From source file:com.meltmedia.dropwizard.etcd.json.EtcdWatchServiceIT.java
@Test public void shouldWatchSingleFileWithNoiseAndTimeout() throws InterruptedException { int eventsCount = 100; // add a directory watch. WatchService service = serviceRule.getService(); CountDownLatch latch = new CountDownLatch(eventsCount); EtcdEventHandler<NodeData> handler = (event) -> { latch.countDown();/*from ww w .jav a2 s . co m*/ }; EtcdDirectoryDao<NodeData> dirDao = new EtcdDirectoryDao<NodeData>(clientRule::getClient, BASE_PATH + "/dir", mapper, NODE_DATA_TYPE); service.registerDirectoryWatch("/dir", NODE_DATA_TYPE, handler); Thread noiseThread = startNoiseThread(externalNoiseDao, 4000); Thread waitThread = startWaitThread(1, TimeUnit.SECONDS); noiseThread.join(); waitThread.join(); startNodeDataThread(dirDao, eventsCount).join(); if (!latch.await(10, TimeUnit.SECONDS)) { throw new IllegalStateException("could not catch up with state."); } }
From source file:com.smartitengineering.cms.maven.tools.plugin.StartMojo.java
public void execute() throws MojoExecutionException { if (solrArtifact != null) { Artifact artifact = getArtifact(solrArtifact); File solrOutDir = new File(outputDirectory, "solr"); solrOutDir.mkdirs();// w w w .j ava 2 s . c o m extract(artifact.getFile(), solrOutDir); } if (eventHubArtifact != null) { Artifact artifact = getArtifact(eventHubArtifact); File hubOutDir = new File(outputDirectory, "hub"); hubOutDir.mkdirs(); extract(artifact.getFile(), hubOutDir); File libDir = new File(new File(hubOutDir, "WEB-INF"), "lib"); { new File(libDir, new StringBuilder("hbase-").append(hbaseVersion).append(".jar").toString()) .delete(); new File(libDir, new StringBuilder("hadoop-core-").append(hadoopVersion).append(".jar").toString()) .delete(); new File(libDir, new StringBuilder("jersey-core-").append(jerseyVersion).append(".jar").toString()) .delete(); new File(libDir, new StringBuilder("jersey-json-").append(jerseyVersion).append(".jar").toString()) .delete(); new File(libDir, new StringBuilder("jersey-server-").append(jerseyVersion).append(".jar").toString()) .delete(); } } if (cmsWebServiceArtifact != null) { Artifact artifact = getArtifact(cmsWebServiceArtifact); File cmsOutDir = new File(outputDirectory, "cms"); cmsOutDir.mkdirs(); extract(artifact.getFile(), cmsOutDir); File libDir = new File(new File(cmsOutDir, "WEB-INF"), "lib"); { new File(libDir, new StringBuilder("hbase-").append(hbaseVersion).append(".jar").toString()) .delete(); new File(libDir, new StringBuilder("hadoop-core-").append(hadoopVersion).append(".jar").toString()) .delete(); new File(libDir, new StringBuilder("jersey-core-").append(jerseyVersion).append(".jar").toString()) .delete(); new File(libDir, new StringBuilder("jersey-json-").append(jerseyVersion).append(".jar").toString()) .delete(); new File(libDir, new StringBuilder("jersey-server-").append(jerseyVersion).append(".jar").toString()) .delete(); } } Thread thread = new Thread(new ToolsSuite()); thread.start(); if (!daemonMode) { try { thread.join(); } catch (Exception ex) { getLog().warn(ex.getMessage(), ex); } } }
From source file:com.espertech.esper.regression.nwtable.TestTableMTGroupedMergeReadMergeWriteSecondaryIndexUpd.java
private void tryMT(int numSeconds) throws Exception { String eplCreateVariable = "create table vartotal (topgroup int primary key, subgroup int primary key, thecnt count(*))"; epService.getEPAdministrator().createEPL(eplCreateVariable); String eplCreateIndex = "create index myindex on vartotal (topgroup)"; epService.getEPAdministrator().createEPL(eplCreateIndex); // populate/*from w w w . j a v a 2 s .c o m*/ String eplInto = "into table vartotal select count(*) as thecnt from LocalGroupEvent.win:length(100) group by topgroup, subgroup"; epService.getEPAdministrator().createEPL(eplInto); // delete empty groups String eplDelete = "on SupportBean_S0 merge vartotal when matched and thecnt = 0 then delete"; epService.getEPAdministrator().createEPL(eplDelete); // seed with {0, 0} group epService.getEPRuntime().sendEvent(new LocalGroupEvent(0, 0)); // select/read String eplMergeSelect = "on SupportBean merge vartotal as vt " + "where vt.topgroup = intPrimitive and vt.thecnt > 0 " + "when matched then insert into MyOutputStream select *"; epService.getEPAdministrator().createEPL(eplMergeSelect); SupportUpdateListener listener = new SupportUpdateListener(); epService.getEPAdministrator().createEPL("select * from MyOutputStream").addListener(listener); WriteRunnable writeRunnable = new WriteRunnable(epService); ReadRunnable readRunnable = new ReadRunnable(epService, listener); // start Thread writeThread = new Thread(writeRunnable); Thread readThread = new Thread(readRunnable); writeThread.start(); readThread.start(); // wait Thread.sleep(numSeconds * 1000); // shutdown writeRunnable.setShutdown(true); readRunnable.setShutdown(true); // join log.info("Waiting for completion"); writeThread.join(); readThread.join(); assertNull(writeRunnable.getException()); assertNull(readRunnable.getException()); assertTrue(writeRunnable.numEvents > 100); assertTrue(readRunnable.numQueries > 100); System.out.println( "Send " + writeRunnable.numEvents + " and performed " + readRunnable.numQueries + " reads"); }
From source file:com.espertech.esper.regression.nwtable.TestTableMTGroupedSubqueryReadMergeWriteSecondaryIndexUpd.java
private void tryMT(int numSeconds) throws Exception { String eplCreateVariable = "create table vartotal (topgroup int primary key, subgroup int primary key)"; epService.getEPAdministrator().createEPL(eplCreateVariable); String eplCreateIndex = "create index myindex on vartotal (topgroup)"; epService.getEPAdministrator().createEPL(eplCreateIndex); // insert and delete merge String eplMergeInsDel = "on LocalGroupEvent as lge merge vartotal as vt " + "where vt.topgroup = lge.topgroup and vt.subgroup = lge.subgroup " + "when not matched and lge.op = 'insert' then insert select lge.topgroup as topgroup, lge.subgroup as subgroup " + "when matched and lge.op = 'delete' then delete"; epService.getEPAdministrator().createEPL(eplMergeInsDel); // seed with {0, 0} group epService.getEPRuntime().sendEvent(new LocalGroupEvent("insert", 0, 0)); // select/read String eplSubselect = "select (select count(*) from vartotal where topgroup=sb.intPrimitive) as c0 " + "from SupportBean as sb"; EPStatement stmtSubselect = epService.getEPAdministrator().createEPL(eplSubselect); SupportUpdateListener listener = new SupportUpdateListener(); stmtSubselect.addListener(listener); WriteRunnable writeRunnable = new WriteRunnable(epService); ReadRunnable readRunnable = new ReadRunnable(epService, listener); // start//from w w w .j a v a 2 s . c o m Thread writeThread = new Thread(writeRunnable); Thread readThread = new Thread(readRunnable); writeThread.start(); readThread.start(); // wait Thread.sleep(numSeconds * 1000); // shutdown writeRunnable.setShutdown(true); readRunnable.setShutdown(true); // join log.info("Waiting for completion"); writeThread.join(); readThread.join(); assertNull(writeRunnable.getException()); assertNull(readRunnable.getException()); assertTrue(writeRunnable.numLoops > 100); assertTrue(readRunnable.numQueries > 100); System.out .println("Send " + writeRunnable.numLoops + " and performed " + readRunnable.numQueries + " reads"); }
From source file:it.unibo.alchemist.boundary.gui.effects.DrawShape.java
@SuppressFBWarnings("ES_COMPARING_STRINGS_WITH_EQ") @Override/*from w ww . java 2 s .c om*/ public void apply(final Graphics2D g, final Node<?> n, final int x, final int y) { if (molString != molStringCached // NOPMD: pointer comparison is wanted here || incarnation == null || curIncarnation != prevIncarnation) { // NOPMD: pointer comparison is wanted here molStringCached = molString; prevIncarnation = curIncarnation; incarnation = SupportedIncarnations.get(curIncarnation.getCurrent()).get(); /* * Process in a separate thread: if it fails, does not kill EDT. */ final Thread th = new Thread(() -> molecule = incarnation.createMolecule(molString)); th.start(); try { th.join(); } catch (final InterruptedException e) { L.error("Bug.", e); } } if (!molFilter || (molecule != null && n.contains(molecule))) { final double ks = (scaleFactor.getVal() - MIN_SCALE) * 2 / (double) (SCALE_DIFF); final int sizex = size.getVal(); final int startx = x - sizex / 2; final int sizey = (int) Math.ceil(sizex * ks); final int starty = y - sizey / 2; final Color toRestore = g.getColor(); colorCache = new Color(red.getVal(), green.getVal(), blue.getVal(), alpha.getVal()); Color newcolor = colorCache; if (molPropertyFilter && molecule != null) { final int minV = (int) (minprop.getVal() * FastMath.pow(PROPERTY_SCALE, propoom.getVal())); final int maxV = (int) (maxprop.getVal() * FastMath.pow(PROPERTY_SCALE, propoom.getVal())); if (minV < maxV) { @SuppressWarnings({ "rawtypes", "unchecked" }) double propval = incarnation.getProperty((Node) n, molecule, property); if (isWritingPropertyValue()) { g.setColor(colorCache); g.drawString(Double.toString(propval), startx + sizex, starty + sizey); } propval = Math.min(Math.max(propval, minV), maxV); propval = (propval - minV) / (maxV - minV); if (reverse) { propval = 1f - propval; } newcolor = c.alter(newcolor, (float) propval); } } g.setColor(newcolor); switch (mode) { case FillEllipse: g.fillOval(startx, starty, sizex, sizey); break; case DrawEllipse: g.drawOval(startx, starty, sizex, sizey); break; case DrawRectangle: g.drawRect(startx, starty, sizex, sizey); break; case FillRectangle: g.fillRect(startx, starty, sizex, sizey); break; default: g.fillOval(startx, starty, sizex, sizey); } g.setColor(toRestore); } }
From source file:org.inaetics.pubsub.impl.discovery.etcd.EtcdWrapperTest.java
@Test public void testEtcdWaitFor() { EtcdWrapper wrapper = new EtcdWrapper(); String directory = "/key"; String value = "value"; try {//w w w . j av a 2s. c om wrapper.createDirectory(directory); wrapper.waitForChange(directory, true, -1, new EtcdCallback() { @Override public void onResult(JsonNode result) { String value2 = result.get("node").get("value").asText(); assertEquals(value, value2); } @Override public void onException(Exception exception) { fail(); } }); Thread thread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(250); wrapper.put("/key/value", value, -1); } catch (Exception e) { e.printStackTrace(); fail(); } } }); thread.start(); thread.join(); } catch (IOException | InterruptedException e) { e.printStackTrace(); fail(); } }
From source file:lockstep.LockstepServer.java
/** * This method puts the server in waiting for client connections. It returns * when the expected number of clients have successfully completed the * handshake./*from ww w .j a v a2 s .c om*/ * Parallel threads are started to handle the handshakes. * In case of failure, all threads are interrupted and then the exception is * propagated. * * @throws IOException In case of failure on opening the ServerSocket and * accepting connections through it * @throws InterruptedException In case of failure during the handshake * sessions */ private void handshakePhase() throws IOException, InterruptedException { ServerSocket tcpServerSocket = new ServerSocket(tcpPort); CyclicBarrier barrier = new CyclicBarrier(this.clientsNumber); CountDownLatch latch = new CountDownLatch(this.clientsNumber); //Each session of the protocol starts with a different random frame number int firstFrameNumber = (new Random()).nextInt(1000) + 100; Thread[] handshakeSessions = new Thread[clientsNumber]; for (int i = 0; i < clientsNumber; i++) { Socket tcpConnectionSocket = tcpServerSocket.accept(); LOG.info("Connection " + i + " accepted from " + tcpConnectionSocket.getInetAddress().getHostAddress()); handshakeSessions[i] = new Thread( () -> serverHandshakeProtocol(tcpConnectionSocket, firstFrameNumber, barrier, latch, this)); handshakeSessions[i].start(); } try { latch.await(); } catch (InterruptedException inEx) { for (Thread handshakeSession : handshakeSessions) handshakeSession.interrupt(); for (Thread handshakeSession : handshakeSessions) handshakeSession.join(); throw new InterruptedException(); } LOG.info("All handshakes completed"); }
From source file:com.vmware.photon.controller.cloudstore.xenon.entity.SchedulingConstantGeneratorTest.java
/** * Test distribution of scheduling constants, creating hosts concurrently on a * single Xenon host./* www. j a va2 s . c o m*/ */ @Test(dataProvider = "HostCounts") public void testSchedulingConstantVariationConcurrent(int hostCount) throws Throwable { List<Long> schedulingConstants = Collections.synchronizedList(new ArrayList<>()); TestEnvironment env = TestEnvironment.create(1); List<Thread> threads = new ArrayList<>(); ServiceHost xenonHost = env.getHosts()[0]; IntStream.range(0, THREADS).forEach((threadId) -> { Thread t = new Thread(() -> { List<Long> thisThreadSchedulingConstants = createHosts(xenonHost, hostCount); schedulingConstants.addAll(thisThreadSchedulingConstants); }); t.start(); threads.add(t); }); for (Thread t : threads) { t.join(); } env.stop(); assertThat(schedulingConstants.size(), equalTo(hostCount * THREADS)); Collections.sort(schedulingConstants); double cv = schedulingConstantGapCV(schedulingConstants); logger.info("Scheduling constant gap coefficient of variation: {}", cv); assertThat(cv, lessThan(MAX_VARIATION)); }
From source file:com.vmware.photon.controller.cloudstore.xenon.entity.SchedulingConstantGeneratorTest.java
/** * Test for distinct scheduling constants, creating hosts concurrently on a * single Xenon host./*w w w. j a v a2 s .c om*/ */ @Test(dataProvider = "HostCounts") public void testDistinctSchedulingConstantsConcurrent(int hostCount) throws Throwable { List<Long> schedulingConstants = Collections.synchronizedList(new ArrayList<>()); TestEnvironment env = TestEnvironment.create(1); List<Thread> threads = new ArrayList<>(); ServiceHost xenonHost = env.getHosts()[0]; IntStream.range(0, THREADS).forEach((threadId) -> { Thread t = new Thread(() -> { List<Long> thisThreadSchedulingConstants = createHosts(xenonHost, hostCount); schedulingConstants.addAll(thisThreadSchedulingConstants); }); t.start(); threads.add(t); }); for (Thread t : threads) { t.join(); } env.stop(); assertThat(schedulingConstants.size(), equalTo(hostCount * THREADS)); // Check that all scheduling constants are distinct (see note in // testDistinctSchedulingConstantsSerial) Set<Long> schedulingConstantsSet = new HashSet<>(); schedulingConstantsSet.addAll(schedulingConstants); assertThat(schedulingConstantsSet.size(), equalTo(schedulingConstants.size())); }