final void test() throws Exception { Future[] futures = new Future[nthreads]; for (int i = 0; i < nthreads; ++i) futures[i] = pool.submit(this); barrier.await(); Thread.sleep(TIMEOUT); boolean tooLate = false; for (int i = 1; i < nthreads; ++i) { if (!futures[i].cancel(true)) tooLate = true; // Unbunch some of the cancels if ((i & 3) == 0) Thread.sleep(1 + rng.next() % 10); } Object f0 = futures[0].get(); if (!tooLate) { for (int i = 1; i < nthreads; ++i) { if (!futures[i].isDone() || !futures[i].isCancelled()) throw new Error("Only one thread should complete"); } } else System.out.print("(cancelled too late) "); long endTime = System.nanoTime(); long time = endTime - timer.startTime; if (print) { double secs = (double) (time) / 1000000000.0; System.out.println("\t " + secs + "s run time"); } }
@Test public void testCoordinateListenerConnectionDiesReconnectAfterTimeout() throws Exception { final CountDownLatch connectedLatch1 = new CountDownLatch(2); final CountDownLatch connectedLatch2 = new CountDownLatch(6); TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1, connectedLatch2); assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); assertEquals( CoordinateListener.Event.COORDINATE_OK, listener.events.get(listener.events.size() - 1)); log.info("Killing connection"); forwarder.terminate(); log.info("Connection down."); Thread.sleep(9000); log.info("Recreating connection soon" + forwarderPort + "->" + zkport); Thread.sleep(1000); assertEquals( CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, listener.events.get(listener.events.size() - 1)); forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport); assertTrue(connectedLatch2.await(20, TimeUnit.SECONDS)); for (int c = 0; c < 100; c++) { if (CoordinateListener.Event.COORDINATE_OK == listener.events.get(listener.events.size() - 1)) { break; } Thread.sleep(300); } Thread.sleep(4500); assertEquals( CoordinateListener.Event.COORDINATE_OK, listener.events.get(listener.events.size() - 1)); forwarder.terminate(); }
@Test public void putFromMultipleThreads() throws InterruptedException { final HazelcastInstance h = Hazelcast.newHazelcastInstance(null); final AtomicInteger counter = new AtomicInteger(0); class Putter implements Runnable { volatile Boolean run = true; public void run() { HazelcastClient hClient = TestUtility.newHazelcastClient(h); while (run) { Map<String, String> clientMap = hClient.getMap("putFromMultipleThreads"); clientMap.put(String.valueOf(counter.incrementAndGet()), String.valueOf(counter.get())); } } }; List<Putter> list = new ArrayList<Putter>(); for (int i = 0; i < 10; i++) { Putter p = new Putter(); list.add(p); new Thread(p).start(); } Thread.sleep(5000); for (Iterator<Putter> it = list.iterator(); it.hasNext(); ) { Putter p = it.next(); p.run = false; } Thread.sleep(100); assertEquals(counter.get(), h.getMap("putFromMultipleThreads").size()); }
/** * Tests the behavior of Zookeeper upon a restart. ZK should clean up old coordinates. * * @throws Exception */ @Test public void testZookeeperRestarts() throws Exception { final CountDownLatch connectedLatch1 = new CountDownLatch(1); final CountDownLatch connectedLatch2 = new CountDownLatch(3); TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1, connectedLatch2); assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); log.info("Killing zookeeper"); forwarder.terminate(); ezk.shutdown(); ezk.del(); ezk.init(); Thread.sleep(2000); forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport); int timeoutSecs = 30; while (--timeoutSecs > 0) { Thread.sleep(1000); } Coordinate c = Coordinate.parse("1.service.user.cell"); cn.createCoordinate(c); Thread.sleep(9000); assertEquals( listener.events.get(listener.events.size() - 1), CoordinateListener.Event.COORDINATE_OK); }
@Test public void removeListener() throws InterruptedException, IOException { HazelcastClient hClient = getHazelcastClient(); final IMap<String, String> map = hClient.getMap("removeListener"); final CountDownLatch entryAddLatch = new CountDownLatch(5); final CountDownLatch entryUpdatedLatch = new CountDownLatch(5); final CountDownLatch entryRemovedLatch = new CountDownLatch(5); CountDownLatchEntryListener<String, String> listener1 = new CountDownLatchEntryListener<String, String>( entryAddLatch, entryUpdatedLatch, entryRemovedLatch); CountDownLatchEntryListener<String, String> listener2 = new CountDownLatchEntryListener<String, String>( entryAddLatch, entryUpdatedLatch, entryRemovedLatch); map.addEntryListener(listener1, true); map.put("hello", "world"); map.put("hello", "new world"); map.remove("hello"); Thread.sleep(100); assertEquals(4, entryAddLatch.getCount()); assertEquals(4, entryRemovedLatch.getCount()); assertEquals(4, entryUpdatedLatch.getCount()); map.removeEntryListener(listener1); map.put("hello", "world"); map.put("hello", "new world"); map.remove("hello"); Thread.sleep(100); assertEquals(4, entryAddLatch.getCount()); assertEquals(4, entryRemovedLatch.getCount()); assertEquals(4, entryUpdatedLatch.getCount()); }
public static void main(String[] args) throws Exception { int maxThreads = 100; if (args.length > 0) maxThreads = Integer.parseInt(args[0]); System.out.print("Warmup:"); for (int j = 0; j < 2; ++j) { int k = 1; for (int i = 1; i <= maxThreads; ) { System.out.print(" " + i); oneTest(i, 10000, false); Thread.sleep(100); if (i == k) { k = i << 1; i = i + (i >>> 1); } else i = k; } } System.out.println(); int k = 1; for (int i = 1; i <= maxThreads; ) { System.out.println("Threads:" + i); oneTest(i, maxIters, true); Thread.sleep(100); if (i == k) { k = i << 1; i = i + (i >>> 1); } else i = k; } }
/** * Testing threads thoroughly seems to be a lot of fun, I am not sure yet how to properly do that. * This test tests priority order and total sum received is equal to total sum sent. It also * simulates clients random hanging. */ @Test public void testReceiveData() { DecorateCheckOrderAndCountSumMarshaller sumAppender = new DecorateCheckOrderAndCountSumMarshaller(); QueueWorker worker = new QueueWorker(sumAppender); Thread workerThread = new Thread(worker); // run 20 clients, 10.000 items will be generated per client as defined in // src/test/properties/app.properties for (int i = 0; i < 20; i++) { Runnable clientHangSimulator = null; if (i % 5 == 0) { // simulate occasional client hang for four of the total twenty clients and check worker is // not biased. clientHangSimulator = () -> { if (ThreadLocalRandom.current().nextInt(1001) % 1000 == 0) { try { Thread.sleep(500L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; } executorService.execute(new DataGeneratorTask(clientHangSimulator)); } workerThread.start(); try { barrier.await(); System.out.println("Fired test"); Thread.sleep(1000); executorService.shutdown(); // runs actually much faster, may need update if item count per client is drastically // increased in app.properties executorService.awaitTermination(2 * 60, TimeUnit.SECONDS); System.out.println("exe service awaited"); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } try { workerThread.join(Long.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } Assert.assertEquals( "Sum generated does not match sum received", sumAppender.getSum(), AppContext.getInstance().getTotalGeneratedAmount()); Assert.assertFalse("Worker didn't exit successfully", workerThread.isAlive()); }
protected void waitForQuiessence() { do { long ltime = _lastTimeOfServerCallable.get(); try { Thread.sleep(150); } catch (InterruptedException e) {; } try { Thread.sleep(150); } catch (InterruptedException ie) {; } if (_lastTimeOfServerCallable.get() == ltime) return; } while (true); }
@Test public void testIssue321_2() throws Exception { HazelcastClient hClient = getHazelcastClient(); final IMap<Integer, Integer> imap = hClient.getMap("testIssue321_2"); final BlockingQueue<EntryEvent<Integer, Integer>> events1 = new LinkedBlockingQueue<EntryEvent<Integer, Integer>>(); final BlockingQueue<EntryEvent<Integer, Integer>> events2 = new LinkedBlockingQueue<EntryEvent<Integer, Integer>>(); imap.addEntryListener( new EntryAdapter() { @Override public void entryAdded(EntryEvent event) { events1.add(event); } }, true); Thread.sleep(50L); imap.addEntryListener( new EntryAdapter() { @Override public void entryAdded(EntryEvent event) { events2.add(event); } }, false); imap.put(1, 1); final EntryEvent<Integer, Integer> event1 = events1.poll(10, TimeUnit.MILLISECONDS); final EntryEvent<Integer, Integer> event2 = events2.poll(10, TimeUnit.MILLISECONDS); assertNotNull(event1); assertNotNull(event2); assertNotNull(event1.getValue()); assertNull(event2.getValue()); }
@Override public Payload call() throws Exception { while (this.callablePayload == null) { Thread.sleep(2); } return this.callablePayload; }
@Test public void lockMap() throws InterruptedException { HazelcastClient hClient = getHazelcastClient(); final IMap<String, String> map = hClient.getMap("lockMap"); final CountDownLatch unlockLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1); map.put("a", "b"); map.lockMap(1, TimeUnit.SECONDS); assertTrue(map.tryPut("a", "c", 10, TimeUnit.MILLISECONDS)); new Thread( new Runnable() { public void run() { assertFalse(map.lockMap(10, TimeUnit.MILLISECONDS)); unlockLatch.countDown(); assertTrue(map.lockMap(Long.MAX_VALUE, TimeUnit.SECONDS)); latch.countDown(); // map.unlockMap(); } }) .start(); assertTrue(unlockLatch.await(10, TimeUnit.SECONDS)); Thread.sleep(2000); map.unlockMap(); assertEquals("c", map.getMapEntry("a").getValue()); assertTrue(latch.await(10, TimeUnit.SECONDS)); }
/** @throws Exception If failed. */ public void testDisabledRest() throws Exception { restEnabled = false; final Grid g = startGrid("disabled-rest"); try { Thread.sleep(2 * TOP_REFRESH_FREQ); // As long as we have round robin load balancer this will cause every node to be queried. for (int i = 0; i < NODES_CNT + 1; i++) assertEquals(NODES_CNT + 1, client.compute().refreshTopology(false, false).size()); final GridClientData data = client.data(PARTITIONED_CACHE_NAME); // Check rest-disabled node is unavailable. try { String affKey; do { affKey = UUID.randomUUID().toString(); } while (!data.affinity(affKey).equals(g.localNode().id())); data.put(affKey, "asdf"); assertEquals("asdf", cache(0, PARTITIONED_CACHE_NAME).get(affKey)); } catch (GridServerUnreachableException e) { // Thrown for direct client-node connections. assertTrue( "Unexpected exception message: " + e.getMessage(), e.getMessage() .startsWith("No available endpoints to connect (is rest enabled for this node?)")); } catch (GridClientException e) { // Thrown for routed client-router-node connections. String msg = e.getMessage(); assertTrue( "Unexpected exception message: " + msg, protocol() == GridClientProtocol.TCP ? msg.contains("No available endpoints to connect (is rest enabled for this node?)") : // TCP router. msg.startsWith( "No available nodes on the router for destination node ID")); // HTTP router. } // Check rest-enabled nodes are available. String affKey; do { affKey = UUID.randomUUID().toString(); } while (data.affinity(affKey).equals(g.localNode().id())); data.put(affKey, "fdsa"); assertEquals("fdsa", cache(0, PARTITIONED_CACHE_NAME).get(affKey)); } finally { restEnabled = true; G.stop(g.name(), true); } }
public void run() { long nextStart = System.currentTimeMillis(); try { while (!dead) { long timeToSleep = nextStart - System.currentTimeMillis(); if (timeToSleep > 10) Thread.sleep(timeToSleep); nextStart += Tickable.TIME_TICK; if ((CMProps.Bools.MUDSTARTED.property()) && (!CMLib.threads().isAllSuspended())) { globalTickCount++; for (Iterator<Exit> iter = exits.iterator(); iter.hasNext(); ) { Exit exit = iter.next(); try { if (!exit.tick(globalTickCount)) exits.remove(exit); } catch (Exception e) { Log.errOut("ServiceEngine", e.toString()); } } for (Iterator<TimeClock> iter = clocks.iterator(); iter.hasNext(); ) { TimeClock clock = iter.next(); try { if (!clock.tick(globalTickCount)) clocks.remove(clock); } catch (Exception e) { Log.errOut("ServiceEngine", e.toString()); } } } } } catch (InterruptedException e) { } }
/* public String tickInfo(String which) { int grpstart=-1; for(int i=0;i<which.length();i++) if(Character.isDigit(which.charAt(i))) { grpstart=i; break; } if(which.equalsIgnoreCase("tickGroupSize")) return ""+ticks.size(); else if(which.toLowerCase().startsWith("tickerssize")) { if(grpstart<0) return""; int group=CMath.s_int(which.substring(grpstart)); if((group>=0)&&(group<ticks.size())) return ""+((Tick)ticks.get(group)).numTickers(); return ""; } int group=-1; int client=-1; int clistart=which.indexOf("-"); if((grpstart>=0)&&(clistart>grpstart)) { group=CMath.s_int(which.substring(grpstart,clistart)); client=CMath.s_int(which.substring(clistart+1)); } if((group<0)||(client<0)||(group>=ticks.size())) return ""; Tick almostTock=(Tick)ticks.get(group); if(client>=almostTock.numTickers()) return ""; TockClient C=null; almostTock.fetchTickerByIndex(client); if(C==null) return ""; if(which.toLowerCase().startsWith("tickername")) { Tickable E=C.clientObject; if(E instanceof Room) return E.ID()+((Room)E).saveNum(); if(E!=null) return E.ID(); return "!NULL!"; } else if(which.toLowerCase().startsWith("tickerstatus")) return ((C.clientObject==null)?"":(""+C.clientObject.getTickStatus())); return ""; } */ public boolean shutdown() { // int numTicks=tickGroup.size(); /*while(ticks.size()>0) { //Log.sysOut("ServiceEngine","Shutting down all tick "+which+"/"+numTicks+"..."); Tick tock=ticks.first(); if(tock!=null) { CMProps.Strings.MUDSTATUS.setProperty("Shutting down...shutting down Service Engine: killing Tick#" + tock.tickObjectCounter+": "+tock.getStatus()); tock.shutdown(); } try{Thread.sleep(100);}catch(Exception e){} }*/ while (areas.size() > 0) { TickArea tock = areas.first(); if (tock != null) { CMProps.Strings.MUDSTATUS.setProperty( "Shutting down...shutting down Service Engine: killing Area#" + tock.tickObjectCounter + ": " + tock.clientObject.getTickStatus()); tock.shutdown(); } try { Thread.sleep(100); } catch (Exception e) { } } CMProps.Strings.MUDSTATUS.setProperty( "Shutting down...shutting down Service Engine: " + ID() + ": thread shutdown"); thread.shutdown(); Log.sysOut("ServiceEngine", "Shutdown complete."); return true; }
public void run() { try { Thread.sleep(MEDIUM_DELAY_MS); } catch (Exception e) { fail("Unexpected exception"); } }
@Test(timeout = 2000) public void testFirehoseFailsAsExpected() { AtomicInteger c = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<>(); firehose(c) .observeOn(Schedulers.computation()) .map( v -> { try { Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } return v; }) .subscribe(ts); ts.awaitTerminalEvent(); System.out.println( "testFirehoseFailsAsExpected => Received: " + ts.valueCount() + " Emitted: " + c.get()); // FIXME it is possible slow is not slow enough or the main gets delayed and thus more than one // source value is emitted. int vc = ts.valueCount(); assertTrue("10 < " + vc, vc <= 10); ts.assertError(MissingBackpressureException.class); }
/** {@inheritDoc} */ @Override public Serializable execute() { int arg = this.<Integer>argument(0); try { if (log.isInfoEnabled()) log.info("Executing job [job=" + this + ", arg=" + arg + ']'); startSignal.countDown(); try { if (!startSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS)) fail(); if (arg == 1) { if (log.isInfoEnabled()) log.info("Job one is proceeding."); } else Thread.sleep(WAIT_TIME); } catch (InterruptedException e) { if (log.isInfoEnabled()) log.info("Job got cancelled [arg=" + arg + ", ses=" + ses + ", e=" + e + ']'); return 0; } if (log.isInfoEnabled()) log.info("Completing job: " + ses); return argument(0); } finally { stopSignal.countDown(); processedCnt++; } }
/** * 延时方法 * * @param ms 毫秒 */ private static final void delay(int ms) { try { Thread.sleep(ms); } catch (Exception e) { e.printStackTrace(); } }
public void run() { try { Thread.sleep(LONG_DELAY_MS); done = true; } catch (Exception e) { } }
public void run() { try { Thread.sleep(MEDIUM_DELAY_MS); fail("should throw exception"); } catch (InterruptedException success) { } }
/* * Launches against the agent& main */ public void testAgentAndMain() throws Exception { Project project = workspace.getProject("p1"); Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun")); bndrun.setProperty("-runpath", "biz.aQute.remote.launcher"); bndrun.setProperty("-runbundles", "bsn-1,bsn-2"); bndrun.setProperty("-runremote", "agent,main;agent=1090"); final RemoteProjectLauncherPlugin pl = (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher(); pl.prepare(); List<? extends RunSession> sessions = pl.getRunSessions(); assertEquals(2, sessions.size()); RunSession agent = sessions.get(0); RunSession main = sessions.get(1); CountDownLatch agentLatch = launch(agent); CountDownLatch mainLatch = launch(main); agent.waitTillStarted(1000); main.waitTillStarted(1000); Thread.sleep(500); agent.cancel(); main.cancel(); agentLatch.await(); mainLatch.await(); assertEquals(-3, agent.getExitCode()); assertEquals(-3, main.getExitCode()); bndrun.close(); }
public void run() { try { Thread.sleep(10); byte[] buf = getBuf(); URL url = new URL("http://127.0.0.1:" + port + "/test"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty( "Content-Type", "Multipart/Related; type=\"application/xop+xml\"; boundary=\"----=_Part_0_6251267.1128549570165\"; start-info=\"text/xml\""); OutputStream out = con.getOutputStream(); out.write(buf); out.close(); InputStream in = con.getInputStream(); byte[] newBuf = readFully(in); in.close(); if (buf.length != newBuf.length) { System.out.println("Doesn't match"); error = true; } synchronized (lock) { ++received; if ((received % 1000) == 0) { System.out.println("Received=" + received); } } } catch (Exception e) { // e.printStackTrace(); System.out.print("."); error = true; } }
public Response callSherpaAndRetry(SAMPMessage message) throws SEDException, SampException { String id = null; for (int i = 0; i < RETRY; i++) { try { Response response = getSampClient().callAndWait(findSherpa(message.get().getMType()), message.get(), 10); if (isException(response)) { throw getException(response); } return response; } catch (SampException ex) { try { Thread.sleep(RETRY_INTERVAL); } catch (InterruptedException e) { } continue; } } String action = "calling"; String msg = "Tried " + action + " Sherpa for " + RETRY + " times every " + RETRY_INTERVAL + " milliseconds. Giving up"; throw new SEDException(msg); }
/** Test for issue #39 */ @Test public void testIsMapKeyLocked() throws InterruptedException { HazelcastClient hClient = getHazelcastClient(); final IMap map = hClient.getMap("testIsMapKeyLocked"); assertFalse(map.isLocked("key")); map.lock("key"); assertTrue(map.isLocked("key")); final CountDownLatch latch = new CountDownLatch(1); Thread thread = new Thread( new Runnable() { public void run() { assertTrue(map.isLocked("key")); try { while (map.isLocked("key")) { Thread.sleep(100); } } catch (InterruptedException e) { throw new RuntimeException(e); } latch.countDown(); } }); thread.start(); Thread.sleep(100); map.unlock("key"); assertTrue(latch.await(3, TimeUnit.SECONDS)); }
public void run() { __log.debug("Starting process definition reaper thread."); long pollingTime = 10000; try { while (true) { Thread.sleep(pollingTime); // Copying the runnning process list to avoid synchronizatMessageExchangeInterion // problems and a potential mess if a policy modifies the list List<ODEProcess> candidates = new ArrayList<ODEProcess>(_registeredProcesses.values()); CollectionsX.remove_if( candidates, new MemberOfFunction<ODEProcess>() { public boolean isMember(ODEProcess o) { return !o.hintIsHydrated(); } }); // And the happy winners are... List<ODEProcess> ripped = _dehydrationPolicy.markForDehydration(candidates); // Bye bye for (ODEProcess process : ripped) { __log.debug("Dehydrating process " + process.getPID()); process.dehydrate(); } } } catch (InterruptedException e) { __log.info(e); } }
@Override public Boolean call() throws Exception { long timeoutMillis = 5000; try { getServersFile(); getZkRunning(); while (true) { while (!restartQueue.isEmpty()) { LOG.debug("Restart queue size [" + restartQueue.size() + "]"); RestartHandler handler = restartQueue.poll(); Future<ScriptContext> runner = pool.submit(handler); ScriptContext scriptContext = runner.get(); // blocking call if (scriptContext.getExitCode() != 0) restartQueue.add(handler); } try { Thread.sleep(timeoutMillis); } catch (InterruptedException e) { } } } catch (Exception e) { e.printStackTrace(); LOG.error(e); pool.shutdown(); throw e; } }
@Test public void testObserveOnWithSlowConsumer() { int NUM = (int) (Observable.bufferSize() * 0.2); AtomicInteger c = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<>(); incrementingIntegers(c) .observeOn(Schedulers.computation()) .map( i -> { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } return i; }) .take(NUM) .subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println( "testObserveOnWithSlowConsumer => Received: " + ts.valueCount() + " Emitted: " + c.get()); assertEquals(NUM, ts.valueCount()); assertTrue(c.get() < Observable.bufferSize() * 2); }
private void sleep() { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }
/** * @param product * @param sequence * @return false if there is an error */ boolean consume(S product, long sequence, long sleep) { if (product == null) return true; // make copies Consumer<S>[] consumers = this.consumers; AtomicLongArray outUse = this.outUse; long[] consumerSeqs = this.consumerSeqs; if (outUse.length() != consumers.length) return false; for (int j = 0; j < consumers.length; j++) { if (!consumers[j].isConsuming()) continue; long time = System.nanoTime(); if (!outUse.compareAndSet(j, 0, time)) continue; try { if (sequence <= consumerSeqs[j]) { outUse.lazySet(j, 0); if (outUse != this.outUse) resetConsumer(consumers[j]); break; } consumerSeqs[j] = sequence; consumers[j].consume(product, time); if (sleep > 0) Thread.sleep(sleep); outUse.lazySet(j, 0); if (outUse != this.outUse) { resetConsumer(consumers[j]); break; } } catch (Exception e) { if (listener == null) logger.error("consume", e); else listener.exceptionThrown(e); } } finishConsuming(product, sequence); return true; }