public void waitInternal(boolean interrupt) { if (queueListener.get() == null) { return; } if (isCurrentThread()) { return; } long MAX_TIMEOUT = 1000 * 10; long start = System.currentTimeMillis(); while (queueListener.get().isRunning()) { try { TimeUnit.MILLISECONDS.sleep(100); Thread thread = queueListener.get().getThread(); if (interrupt) { if (thread != null) { thread.interrupt(); } } else if (System.currentTimeMillis() - start > MAX_TIMEOUT) { if (thread != null) { String msg = "Waited for " + MAX_TIMEOUT + "ms, will now interrupt the thread"; log.warn(msg); thread.interrupt(); throw new RuntimeException(msg); } } } catch (InterruptedException e) { log.trace("Got Interrupted while waiting for tasks.", e); } } }
@Test public void testBaseMetaChange() throws Exception { startEngine(); m_curator .setData() .forPath(ZKPathUtils.getBaseMetaVersionZkPath(), ZKSerializeUtils.serialize(100L)); int retries = 50; int i = 0; while (m_baseMetaChangeCount.get() != 1 && i++ < retries) { TimeUnit.MILLISECONDS.sleep(100); } assertEquals(1, m_baseMetaChangeCount.get()); m_curator .setData() .forPath(ZKPathUtils.getBaseMetaVersionZkPath(), ZKSerializeUtils.serialize(200L)); i = 0; while (m_baseMetaChangeCount.get() != 2 && i++ < retries) { TimeUnit.MILLISECONDS.sleep(100); } assertEquals(2, m_baseMetaChangeCount.get()); }
@Test(timeout = 60000) public void testNotIdledWhenInUse() throws Exception { pooledFactory.setIdleTimeout(10); PooledConnection connection = (PooledConnection) pooledFactory.createConnection(); Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // let connection to get idle TimeUnit.MILLISECONDS.sleep(500); // get a connection from pool again, it should be the same underlying connection // as before and should not be idled out since an open session exists. PooledConnection connection2 = (PooledConnection) pooledFactory.createConnection(); assertSame(connection.getConnection(), connection2.getConnection()); // now the session is closed even when it should not be try { // any operation on session first checks whether session is closed s.getTransacted(); } catch (javax.jms.IllegalStateException e) { assertTrue("Session should be fine, instead: " + e.getMessage(), false); } Connection original = connection.getConnection(); connection.close(); connection2.close(); // let connection to get idle TimeUnit.MILLISECONDS.sleep(500); // get a connection from pool again, it should be a new Connection instance as the // old one should have been inactive and idled out. PooledConnection connection3 = (PooledConnection) pooledFactory.createConnection(); assertNotSame(original, connection3.getConnection()); }
/* * (non-Javadoc) * * @see java.lang.Thread#run() */ public void run() { try { while (true) { if (Manager.instance().canDump()) { Manager.instance().setProfileFlag(true); TimeUnit.SECONDS.sleep(eachProfUseTime); Manager.instance().setProfileFlag(false); // 等待已开始的End方法执行完成 TimeUnit.MILLISECONDS.sleep(500L); dumpProfileData(); } TimeUnit.SECONDS.sleep(eachProfIntervalTime); } } catch (Exception e) { e.printStackTrace(); } finally { Manager.instance().setProfileFlag(false); if (fileWriter != null) { fileWriter.closeFile(); } // 等待已开始的End方法执行完成 try { TimeUnit.MILLISECONDS.sleep(500L); } catch (InterruptedException e) { e.printStackTrace(); } Profiler.clearData(); } }
public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) exec.execute(new Task()); exec.execute(new Task2()); Timer timer = new Timer(); timer.scheduleAtFixedRate( new TimerTask() { boolean prod = true; public void run() { if (prod) { System.out.print("\nnotify() "); Task.blocker.prod(); prod = false; } else { System.out.print("\nnotifyAll() "); Task.blocker.prodAll(); prod = true; } } }, 400, 400); // Run every .4 second TimeUnit.SECONDS.sleep(5); // Run for a while... timer.cancel(); System.out.println("\nTimer canceled"); TimeUnit.MILLISECONDS.sleep(500); System.out.print("Task2.blocker.prodAll() "); Task2.blocker.prodAll(); TimeUnit.MILLISECONDS.sleep(500); System.out.println("\nShutting down"); exec.shutdownNow(); // Interrupt all tasks }
@Test public void testScheduleFixedRateCallable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); assertThat(completed.getCount()).isZero(); assertThat(duration.getCount()).isZero(); assertThat(scheduledOnce.getCount()).isZero(); assertThat(scheduledRepetitively.getCount()).isZero(); assertThat(scheduledOverrun.getCount()).isZero(); assertThat(percentOfPeriod.getCount()).isZero(); ScheduledFuture<?> theFuture = instrumentedScheduledExecutor.scheduleAtFixedRate( new Runnable() { public void run() { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isEqualTo(1); assertThat(scheduledOnce.getCount()).isEqualTo(0); assertThat(scheduledRepetitively.getCount()).isEqualTo(1); try { TimeUnit.MILLISECONDS.sleep(50); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } return; } }, 10L, 10L, TimeUnit.MILLISECONDS); TimeUnit.MILLISECONDS.sleep(100); theFuture.cancel(true); TimeUnit.MILLISECONDS.sleep(100); assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); assertThat(completed.getCount()).isNotEqualTo(0); assertThat(duration.getCount()).isNotEqualTo(0); assertThat(duration.getSnapshot().size()).isNotEqualTo(0); assertThat(scheduledOnce.getCount()).isZero(); assertThat(scheduledRepetitively.getCount()).isEqualTo(1); assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); }
/** Called by Felix DM when starting this component. */ protected void start() throws Exception { // start calculating avg m_avgExecutor = Executors.newSingleThreadExecutor(); m_avgFuture = m_avgExecutor.submit( () -> { long oldTimeMillis = System.currentTimeMillis(); while (!Thread.currentThread().isInterrupted()) { try { long processedCount = getProcessedCount(); long currentTimeMillis = System.currentTimeMillis(); m_processedAvg = (1000.0 * processedCount) / (currentTimeMillis - oldTimeMillis); oldTimeMillis = currentTimeMillis; TimeUnit.MILLISECONDS.sleep(900); } catch (InterruptedException e) { // Break out of our loop... Thread.currentThread().interrupt(); } catch (Exception e) { // Ignore, not much we can do about this... info( "Failed to process sample(s)! Cause: %s", (e.getMessage() == null ? "NullPointerException" : e.getMessage())); } } }); // start producing m_processExecutor = Executors.newSingleThreadExecutor(); m_processFuture = m_processExecutor.submit( () -> { while (!Thread.currentThread().isInterrupted() && !m_processExecutor.isShutdown()) { try { processSampleData(); TimeUnit.MILLISECONDS.sleep(getTaskInterval()); } catch (InterruptedException e) { // Break out of our loop... Thread.currentThread().interrupt(); } catch (Exception e) { // Ignore, not much we can do about this... info( "Failed to process sample(s)! Cause: %s", (e.getMessage() == null ? "NullPointerException" : e.getMessage())); } } }); info("Processor %s started...", getName()); }
private void sleep(long sleepTime) { try { TimeUnit.MILLISECONDS.sleep(sleepTime); } catch (InterruptedException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } }
public void receive() throws IOException, InterruptedException { Socket socket = null; socket = serverSocket.accept(); BufferedReader br = getReader(socket); for (int i = 0; i < 20; i++) { String msg = br.readLine(); System.out.println("receive:" + msg); TimeUnit.MILLISECONDS.sleep(1000); if (i == 2) { if (stopWay == SUDDEN_STOP) { System.out.println("突然终止程序"); System.exit(0); } if (stopWay == SOCKET_STOP) { System.out.println("关闭Socket并终止程序"); socket.close(); break; } if (stopWay == INPUT_STOP) { System.out.println("关闭输入流并终止程序"); socket.shutdownInput(); break; } if (stopWay == SERVERSOCKET_STOP) { System.out.println("关闭ServerSocket并终止程序"); serverSocket.close(); break; } } } if (stopWay == NATURAL_STOP) { socket.close(); serverSocket.close(); } }
public void chew() { try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }
/* ------------------------------------------------------------ */ @Test @Slow public void testDateCache() throws Exception { // @WAS: Test t = new Test("org.eclipse.jetty.util.DateCache"); // 012345678901234567890123456789 DateCache dc = new DateCache("EEE, dd MMM yyyy HH:mm:ss zzz ZZZ", Locale.US); dc.setTimeZone(TimeZone.getTimeZone("GMT")); Thread.sleep(2000); long now = System.currentTimeMillis(); long end = now + 3000; String f = dc.format(now); String last = f; int hits = 0; int misses = 0; while (now < end) { last = f; f = dc.format(now); // System.err.printf("%s %s%n",f,last==f); if (last == f) hits++; else misses++; TimeUnit.MILLISECONDS.sleep(50); now = System.currentTimeMillis(); } Assert.assertTrue(hits / 10 > misses); }
@Test public void testSendWithTaskQueueFull() throws Exception { brokerActionsWhenReceivedSendMessageCmd( // MessageSendAnswer.NoOp // ); int times = Integer.valueOf(lookup(ProducerConfig.class).getBrokerSenderTaskQueueSize()) + 2; List<Future<SendResult>> futures = new ArrayList<Future<SendResult>>(times); List<Pair<String, String>> appProperties = Arrays.asList(new Pair<String, String>("a", "A")); for (int i = 0; i < times; i++) { futures.add(sendAsync(TEST_TOPIC, "pKey", "body", "rKey", appProperties, false, null)); if (i == 0) { TimeUnit.MILLISECONDS.sleep( Integer.valueOf( lookup(ProducerConfig.class).getBrokerSenderNetworkIoCheckIntervalMaxMillis()) + 100L); } } for (int i = 0; i < times - 1; i++) { assertFalse(futures.get(i).isDone()); } try { futures.get(times - 1).get(); fail(); } catch (ExecutionException e) { if (!(e.getCause() instanceof MessageSendException)) { fail(); } } catch (Exception e) { fail(); } }
private void sleep(TsInformationType type) { try { TimeUnit.MILLISECONDS.sleep(type.needsData() ? 2000 : 150); } catch (InterruptedException ex) { throw new RuntimeException(ex); } }
// Insert a random delay to produce the effect // of a calculation time: private void pause(int factor) { try { TimeUnit.MILLISECONDS.sleep(100 + rand.nextInt(factor)); } catch (InterruptedException e) { print("sleep() interrupted"); } }
static void test(Runnable r) throws InterruptedException { Future<?> f = exec.submit(r); TimeUnit.MILLISECONDS.sleep(100); System.out.println("Interrupted " + r.getClass().getName()); f.cancel(true); System.out.println("Interrupt send to " + r.getClass().getName()); }
public static void main(String[] args) { int radius = 500; SmileyModel test = new SmileyModel(radius, true); FirstSmileyPanel view = new FirstSmileyPanel(test); AAPCEventPrinter ep = new AAPCEventPrinter(); test.addPropertyChangeListener(ep); JFrame frame = new JFrame("Smiley of DOOM!!!"); Container container = frame.getContentPane(); container.add(view); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 600); frame.setVisible(true); int i = 0; while (true) { test.rotateEye(i); i += 10; if (i % 90 == 0) { test.changeSmile(); test.setSmile(true); // test.setSize(radius+=20); } try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
@Slow @Test public void testTimeoutIsCancelledOnSuccess() throws Exception { long timeout = 1000; start(new TimeoutHandler(timeout)); final CountDownLatch latch = new CountDownLatch(1); final byte[] content = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; Request request = client .newRequest("localhost", connector.getLocalPort()) .scheme(scheme) .content(new InputStreamContentProvider(new ByteArrayInputStream(content))); request.send( new TimedResponseListener( 2 * timeout, TimeUnit.MILLISECONDS, request, new BufferingResponseListener() { @Override public void onComplete(Result result) { Assert.assertFalse(result.isFailed()); Assert.assertArrayEquals(content, getContent()); latch.countDown(); } })); Assert.assertTrue(latch.await(3 * timeout, TimeUnit.MILLISECONDS)); TimeUnit.MILLISECONDS.sleep(2 * timeout); Assert.assertNull(request.getAbortCause()); }
@Override public void run() { try { m_channelManager = new ClientChannelManager(); long expireTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(1); while (m_channelManager.getActiveChannel() == null && System.currentTimeMillis() < expireTime) { TimeUnit.MILLISECONDS.sleep(1); } m_warmup.countDown(); run0(); } catch (Throwable e) { m_logger.error(e.getMessage(), e); m_warmup.countDown(); } finally { if (m_channelManager != null) { m_channelManager.close(); } m_latch.countDown(); } }
@Slow @Test public void testTimeoutIsCancelledOnSuccessWithExplicitConnection() throws Exception { long timeout = 1000; start(new TimeoutHandler(timeout)); final CountDownLatch latch = new CountDownLatch(1); Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort()); try (Connection connection = destination.newConnection().get(5, TimeUnit.SECONDS)) { Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scheme); connection.send( request, new TimedResponseListener(2 * timeout, TimeUnit.MILLISECONDS, request) { @Override public void onComplete(Result result) { Response response = result.getResponse(); Assert.assertEquals(200, response.getStatus()); Assert.assertFalse(result.isFailed()); latch.countDown(); } }); Assert.assertTrue(latch.await(3 * timeout, TimeUnit.MILLISECONDS)); TimeUnit.MILLISECONDS.sleep(2 * timeout); Assert.assertNull(request.getAbortCause()); } }
public static void main(String[] args) throws InterruptedException { for (int i = 30; i >= 0; i--) { System.out.println(i); TimeUnit.MILLISECONDS.sleep(100); } System.out.println("Бум!"); }
@Override public void run() { long cycles = 0L; try { long startTime = System.currentTimeMillis(); long lastStatus = startTime; info("Starting time:" + startTime); info("Running until:" + (startTime + MAX_RUN_TIME)); for (long currentTime = System.currentTimeMillis(); currentTime < startTime + MAX_RUN_TIME; currentTime = System.currentTimeMillis()) { if (CHATTY) { info("" + currentTime + ": Executing GET"); } else if (lastStatus + 1000 < currentTime) { lastStatus = currentTime; info("Processing... (Cycles : " + cycles + ")"); } RestClient client = new RestClient(workerSettings); client.remoteEsVersion(); client.close(); cycles++; if (SLEEP) TimeUnit.MILLISECONDS.sleep(SLEEP_TIME); } info("Completed test without exhaustion."); info("Cycles completed: " + cycles); } catch (Exception e) { error( "Completed test with example of socket exhaustion. Cycles completed at failure: " + cycles, e); } }
protected void sleep() { try { TimeUnit.MILLISECONDS.sleep(WAIT_PARTITION_TABLE_UPDATE_MILLIS); } catch (InterruptedException e) { throw ExceptionUtil.rethrow(e); } }
@Test public void testFailIfNoConsumersAfterConsumersLeave() throws Exception { context.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("direct-vm:foo").routeId("stopThisRoute").to("mock:foo"); } }); context.start(); getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World"); template.sendBody("direct-vm:foo", "Hello World"); assertMockEndpointsSatisfied(); context.stopRoute("stopThisRoute"); TimeUnit.MILLISECONDS.sleep(100); try { template.sendBody("direct-vm:foo", "Hello World"); fail("Should throw an exception"); } catch (CamelExecutionException e) { assertIsInstanceOf(DirectVmConsumerNotAvailableException.class, e.getCause()); } }
@Override public void run() { try { while (!Thread.interrupted()) { synchronized (this) { while (restaurant.meal != null) { wait(); } } if (++count == 11) { System.out.println("菜上齐了"); // 这块只是向 chef 和 waiter 发送一个 interrupt 信号 // 但是因为 synchronized 和 IO 是不能被中断的,所以这里会通过可中断的 // sleep()抛出 InterruptedException。 // 而 waiter 只能通过 while(Thread.interrupted())抛出的 InterruptedException返回 // 而且我们会发现,多做了一个菜!本来做了10个就够了。11个本意想关闭程序,但是因为 // synchronized 无法中断,只好又做了一个菜(厨师也饿了)。但是因为服务员在 wait(),可以被中断 // 所以做好的菜没有被服务员上去。。。。 restaurant.exec.shutdownNow(); } System.out.print("做菜ing..."); synchronized (restaurant.waiter) { restaurant.meal = new Meal(count); restaurant.waiter.notifyAll(); } TimeUnit.MILLISECONDS.sleep(100); } } catch (InterruptedException e) { System.out.println("chef interrupted"); } }
@Override public void run() { while (!Thread.interrupted()) { try { selector.select(); } catch (IOException e) { continue; } processRegisterChannels(); Set<SelectionKey> keys = selector.selectedKeys(); for (SelectionKey key : keys) { try { handle(key); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable throwable) { Logger.error("ChannelKey handle fail.", throwable); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } keys.clear(); } }
private void someLongProcess(List<String> mock) { try { TimeUnit.MILLISECONDS.sleep(100); mock.add("test"); } catch (InterruptedException e) { } }
static void shutdownDomain( final DomainClient client, final Map<ServerIdentity, ServerStatus> servers) { final ModelNode address = new ModelNode().setEmptyList().add("host", "master"); try { // First shutdown the servers ModelNode op = Operations.createOperation("stop-servers"); ModelNode response = client.execute(op); if (Operations.isSuccessfulOutcome(response)) { op = Operations.createOperation("shutdown", address); response = client.execute(op); if (Operations.isSuccessfulOutcome(response)) { // Wait until the process has died while (true) { if (isDomainRunning(client, servers, true)) { try { TimeUnit.MILLISECONDS.sleep(20L); } catch (InterruptedException e) { LOGGER.debug("Interrupted during sleep", e); } } else { break; } } } else { LOGGER.debugf("Failed to execute %s: %s", op, Operations.getFailureDescription(response)); } } else { LOGGER.debugf("Failed to execute %s: %s", op, Operations.getFailureDescription(response)); } } catch (IOException e) { LOGGER.debug("Error shutting down domain", e); } }
@Override public R apply(final D input) { RuntimeException rootCause = null; for (int i = 0; i < retries; i++) { EntityTransaction db = Entities.get(this.entityType); try { R ret = this.function.apply(input); db.commit(); return ret; } catch (RuntimeException ex) { db.rollback(); if (Exceptions.isCausedBy(ex, OptimisticLockException.class)) { rootCause = Exceptions.findCause(ex, OptimisticLockException.class); } else if (Exceptions.isCausedBy(ex, LockAcquisitionException.class)) { rootCause = Exceptions.findCause(ex, LockAcquisitionException.class); } else { rootCause = ex; Logs.extreme().error(ex, ex); throw ex; } try { TimeUnit.MILLISECONDS.sleep(20); } catch (InterruptedException ex1) { Exceptions.maybeInterrupted(ex1); } continue; } } throw (rootCause != null ? rootCause : new NullPointerException( "BUG: Transaction retry failed but root cause exception is unknown!")); }
private void run0() throws InterruptedException { ByteBufAllocator allocator = m_descriptor.getByteBufAllocator(); int initialCapacity = 4 * 1024; // 4K ByteBuf buf = allocator.buffer(initialCapacity); TransportHub hub = m_descriptor.getHub(); while (m_active.get()) { Channel channel = m_channelManager.getActiveChannel(); if (channel != null && channel.isWritable()) { do { if (hub.fill(buf)) { channel.writeAndFlush(buf); buf = allocator.buffer(initialCapacity); } else { break; } } while (channel.isWritable()); } TimeUnit.MILLISECONDS.sleep(1); // 1ms } long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(3); // 3s timeout while (true) { Channel channel = m_channelManager.getActiveChannel(); if (channel != null && channel.isWritable()) { do { if (hub.fill(buf)) { channel.writeAndFlush(buf); buf = allocator.buffer(initialCapacity); } else { break; } } while (channel.isWritable()); } if (System.currentTimeMillis() >= end) { throw new InterruptedException("Timeout with messages left in the queue!"); } TimeUnit.MILLISECONDS.sleep(1); // 1ms } }
private void waitUntilConsumerStarted(ConsumerHolder holder) { while (!((DefaultConsumerHolder) holder).isConsuming()) { try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }