Example usage for java.lang Object wait

List of usage examples for java.lang Object wait

Introduction

In this page you can find the example usage for java.lang Object wait.

Prototype

public final native void wait(long timeoutMillis) throws InterruptedException;

Source Link

Document

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

Usage

From source file:com.liveramp.hank.test.ZkTestCase.java

@Before
public final void setUpZk() throws Exception {

    setupZkServer();/*from   w  ww .  j  ava2s . c  o m*/

    final Object lock = new Object();
    final AtomicBoolean connected = new AtomicBoolean(false);

    zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None:
                if (event.getState() == KeeperState.SyncConnected) {
                    connected.set(true);
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }
            }
            LOG.debug(event.toString());
        }
    });

    synchronized (lock) {
        lock.wait(2000);
    }
    if (!connected.get()) {
        fail("timed out waiting for the zk client connection to come online!");
    }
    LOG.debug("session timeout: " + zk.getSessionTimeout());

    zk.deleteNodeRecursively(zkRoot);
    WaitUntil.orDie(() -> {
        try {
            return zk.exists(zkRoot, false) == null;
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    createNodeRecursively(zkRoot);
}

From source file:com.taobao.gecko.service.impl.DefaultRemotingClient.java

@Override
public void awaitReadyInterrupt(final String group, final long time)
        throws NotifyRemotingException, InterruptedException {
    if (StringUtils.isBlank(group)) {
        throw new IllegalArgumentException("Blank group");
    }/*from ww  w .ja v a2  s  . co m*/
    // 
    final Object readyLock = this.getAttribute(group, Constants.GROUP_CONNECTION_READY_LOCK);
    final Object attribute = this.getAttribute(group, Constants.CONNECTION_COUNT_ATTR);
    if (readyLock == null || attribute == null) {
        throw new IllegalStateException("connect");
    } else {
        final int maxConnCount = (Integer) attribute;
        long totalTime = 0;
        synchronized (readyLock) {
            while (this.getConnectionCount(group) != maxConnCount) {
                final long start = System.currentTimeMillis();
                readyLock.wait(1000);
                totalTime += System.currentTimeMillis() - start;
                if (totalTime >= time) {
                    throw new NotifyRemotingException("" + time + "");
                }
            }
        }
    }

}

From source file:org.limewire.mojito.db.DHTValueTest.java

public void testLocationCount() throws Exception {
    int k = KademliaSettings.REPLICATION_PARAMETER.getValue();

    Map<KUID, MojitoDHT> dhts = Collections.emptyMap();
    try {/*from   ww  w  .  j av a2  s.co  m*/
        dhts = MojitoUtils.createBootStrappedDHTsMap(2);
        Thread.sleep(250);

        KUID key = KUID.createRandomID();
        DHTValueType type = DHTValueType.TEST;
        Version version = Version.ZERO;
        byte[] b = StringUtils.toUTF8Bytes("Hello World");

        long time = System.currentTimeMillis();

        Context context = (Context) dhts.values().iterator().next();

        final Object lock = new Object();
        final Storable storable = new Storable(key, new DHTValueImpl(type, version, b));

        // Pre-Condition
        assertEquals(0, storable.getLocationCount());
        assertEquals(0L, storable.getPublishTime());
        assertTrue(DatabaseUtils.isPublishingRequired(storable));

        // Store...
        DHTFuture<StoreResult> future = context.store(storable);
        future.addDHTFutureListener(new DHTFutureAdapter<StoreResult>() {
            @Override
            public void handleFutureSuccess(StoreResult result) {
                storable.handleStoreResult(result);
                synchronized (lock) {
                    lock.notifyAll();
                }
            }
        });

        future.get();
        synchronized (lock) {
            if (storable.getLocationCount() == 0L) {
                lock.wait(1000L);
            }
        }

        // Post-Condition
        assertEquals(k, storable.getLocationCount());
        assertGreaterThanOrEquals(time, storable.getPublishTime());
        assertFalse(DatabaseUtils.isPublishingRequired(storable));

    } finally {
        for (MojitoDHT dht : dhts.values()) {
            dht.close();
        }
    }
}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

public void testSendRateWithActivatingConsumers() throws Exception {
    final Destination destination = createDestination();
    final ConnectionFactory factory = createConnectionFactory();
    startInactiveConsumers(factory, destination);

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = createMessageProducer(session, destination);

    // preload the durable consumers
    double[] inactiveConsumerStats = produceMessages(destination, 500, 10, session, producer, null);
    LOG.info("With inactive consumers: ave: " + inactiveConsumerStats[1] + ", max: " + inactiveConsumerStats[0]
            + ", multiplier: " + (inactiveConsumerStats[0] / inactiveConsumerStats[1]));

    // periodically start a durable sub that has a backlog
    final int consumersToActivate = 5;
    final Object addConsumerSignal = new Object();
    Executors.newCachedThreadPool(new ThreadFactory() {
        @Override//from  w w  w  .j a va  2s.co  m
        public Thread newThread(Runnable r) {
            return new Thread(r, "ActivateConsumer" + this);
        }
    }).execute(new Runnable() {
        @Override
        public void run() {
            try {
                MessageConsumer consumer = null;
                for (int i = 0; i < consumersToActivate; i++) {
                    LOG.info("Waiting for add signal from producer...");
                    synchronized (addConsumerSignal) {
                        addConsumerSignal.wait(30 * 60 * 1000);
                    }
                    TimedMessageListener listener = new TimedMessageListener();
                    consumer = createDurableSubscriber(factory.createConnection(), destination,
                            "consumer" + (i + 1));
                    LOG.info("Created consumer " + consumer);
                    consumer.setMessageListener(listener);
                    consumers.put(consumer, listener);
                }
            } catch (Exception e) {
                LOG.error("failed to start consumer", e);
            }
        }
    });

    double[] statsWithActive = produceMessages(destination, 500, 10, session, producer, addConsumerSignal);

    LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + statsWithActive[0]
            + ", multiplier: " + (statsWithActive[0] / statsWithActive[1]));

    while (consumers.size() < consumersToActivate) {
        TimeUnit.SECONDS.sleep(2);
    }

    long timeToFirstAccumulator = 0;
    for (TimedMessageListener listener : consumers.values()) {
        long time = listener.getFirstReceipt();
        timeToFirstAccumulator += time;
        LOG.info("Time to first " + time);
    }
    LOG.info("Ave time to first message =" + timeToFirstAccumulator / consumers.size());

    for (TimedMessageListener listener : consumers.values()) {
        LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(10000) + " max receipt: "
                + listener.maxReceiptTime);
    }

    //assertTrue("max (" + statsWithActive[0] + ") within reasonable
    // multiplier of ave (" + statsWithActive[1] + ")",
    //        statsWithActive[0] < 5 * statsWithActive[1]);

    // compare no active to active
    LOG.info("Ave send time with active: " + statsWithActive[1] + " as multiplier of ave with none active: "
            + inactiveConsumerStats[1] + ", multiplier=" + (statsWithActive[1] / inactiveConsumerStats[1]));

    assertTrue(
            "Ave send time with active: " + statsWithActive[1]
                    + " within reasonable multpler of ave with none active: " + inactiveConsumerStats[1]
                    + ", multiplier " + (statsWithActive[1] / inactiveConsumerStats[1]),
            statsWithActive[1] < 15 * inactiveConsumerStats[1]);
}

From source file:fi.solita.phantomrunner.jetty.PhantomWebSocketHandler.java

public JsonNode sendMessageToConnections(String msg) {
    try {/*from  w  w w . j  a v a  2  s.com*/
        final Object requestLock = new Object();
        final AtomicReference<JsonNode> result = new AtomicReference<JsonNode>();

        synchronized (socketLock) {
            if (socket.get() == null) {
                // wait for 10 secs for the socket to open
                socketLock.wait(TimeUnit.SECONDS.toMillis(10));
            }
        }

        if (socket.get() == null) {
            throw new PhantomWebSocketException("No open websocket connection available, cannot send message");
        }

        try {
            socket.get().send(msg, new PhantomMessageListener() {
                @Override
                public void message(JsonNode readTree) {
                    synchronized (requestLock) {
                        result.set(readTree);
                        requestLock.notifyAll();
                    }
                }
            });
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        synchronized (requestLock) {
            requestLock.wait(10000);
        }

        return result.get();
    } catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }
}

From source file:org.logicblaze.lingo.cache.ClusteredCacheManager.java

/**
 * Wait around up to some timeout period until the local transaction
 * has been distributed around the cluster and applied locally to the backing
 * cache//from w  w  w  .  j  a  v  a 2s . co m
 */
protected void waitUntilTransactionApplied(Object lock, String originator) {
    // One strategy could be to not wait at all
    // and just use the local transaction view.
    // To do this we'd need to be able to snapshot the local changes
    // to a savepoint
    // so that a rollback after a commit() would only rollback the new changes
    // since the last savepoint. The savepoints can be discarded when the transaction
    // is eventually applied to the backing cache
    //
    // however we'd never be able to fail a transaction with
    // an optimistic transaction failure - but it would be super fast :)

    while (hasLockFor(originator)) {
        try {
            if (log.isTraceEnabled()) {
                log.trace("Waiting for transaction to commit for originator: " + originator + " with lock: "
                        + lock);
            }
            System.out.println("Waiting for transaction to commit ===>");
            synchronized (lock) {
                // TODO we might wanna add some timeout or retries here
                lock.wait(2000L);

                if (log.isTraceEnabled()) {
                    log.trace("Transaction commited for originator: " + originator + " with lock: " + lock);
                }
                return;
            }
        } catch (InterruptedException e) {
            log.trace("Ignored interupted exception: " + e, e);
        }
    }
}

From source file:com.visionspace.jenkins.vstart.plugin.VSPluginPerformer.java

public Long runVstart(Long id, BuildListener listener, int timeInterval) {
    try {//from  w w w. ja v a  2s  . co m
        //Run VSTART
        org.json.JSONObject runObject = vstObject.run(id);
        listener.getLogger().println("\nVSTART is now running!");
        Long reportId = runObject.getLong("reportId");

        //Inform which test case is running
        //listener.getLogger().println("The test case " + vstObject.getTestCase(testCaseId) + "has started.");

        //For concurrency issues
        Object obj = new Object();

        synchronized (obj) {
            long timeStamp = 0;
            org.json.JSONObject logger = null;

            do {
                logger = vstObject.getLog(reportId, timeStamp);
                JSONArray jArray = logger.getJSONArray("log");
                for (int i = 0; i < jArray.length(); i++) {
                    org.json.JSONObject json = jArray.getJSONObject(i);
                    Long eventTimeStamp = json.getLong("timestamp");
                    Date date = new Date(eventTimeStamp);
                    listener.getLogger().println(json.getString("level") + " " + /*eventTimeStamp*/date + " ["
                            + json.getString("resource") + "]" + " - " + json.getString("message") + "\n");

                    //Stores the latest timestamp
                    if (eventTimeStamp > timeStamp) {
                        timeStamp = eventTimeStamp;
                    }
                }
                if (!logger.getBoolean("finished")) {
                    obj.wait(timeInterval);
                }
            } while (!logger.getBoolean("finished"));
        }

        //inform the finishing of the test case execution
        //listener.getLogger().println("The test case " + vstObject.getTestCase(testCaseId) + "has finished its execution.");

        //Finished run
        listener.getLogger().println("VSTART run has now ended!");

        return reportId;
    } catch (URISyntaxException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Exception during the VSTART run! -> " + ex.getReason());
        return 0l;
    } catch (IOException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Exception during the VSTART run! -> " + ex.getMessage());
        return 0l;
    } catch (InterruptedException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Exception during the VSTART run! -> " + ex.getMessage());
        return 0l;
    }
}

From source file:io.kahu.hawaii.cucumber.glue.html.HtmlSteps.java

@When("^I wait (\\d+) seconds?$")
public void I_wait_seconds(int seconds) throws Throwable {
    if (seconds > 0) {
        int millis = seconds * 1000;
        Object lock = new Object();
        synchronized (lock) {
            try {
                lock.wait(millis);
            } catch (InterruptedException e) {
                // ignore
            }/*ww w . ja v  a  2 s . c o  m*/
        }
    }
}

From source file:io.kahu.hawaii.cucumber.glue.html.HtmlSteps.java

public void acceptCookies() {
    // accept cookies popup
    if (acceptCookies) {
        try {/*ww  w .  j a  v a  2s  .co m*/
            WebDriverWait wait = new WebDriverWait(webDriver, 2); // wait
            // max 2
            // seconds
            wait.until(ExpectedConditions.elementToBeClickable(By.className("cookie-yes")));
            turnOffImplicitWaits();
            WebElement element = findElement(By.className("cookie-yes"));
            moveTo(element).click().perform();
            Object lock = new Object();
            synchronized (lock) {
                try {
                    lock.wait(1000); // wait 1 second to allow cookie popup
                    // to be closed
                } catch (InterruptedException e) {
                    // ignore
                }
            }

        } catch (NoSuchElementException e) {
            // ignore, cookie popup not displayed
        } catch (TimeoutException e) {
            // ignore, cookie popup not displayed
        }
        turnOnImplicitWaits();
        acceptCookies = false;
    }
}

From source file:org.silverpeas.core.persistence.jdbc.JdbcSqlQueryIT.java

@SuppressWarnings("UnusedDeclaration")
private List<String> executeMultiThreadedOperations(final boolean rollbackInTransaction) throws Exception {
    final Object monitorOfDeletion = new Object();
    final Object monitorOfVerification = new Object();
    assertThat(getTableLines(), hasSize((int) NB_ROW_AT_BEGINNING));
    final List<String> result = new ArrayList<>();
    Thread deletionProcess = new Thread(() -> {
        try {//from   www. j  a  v  a  2s  .  c  o  m
            Transaction.performInOne(() -> {
                try (final Connection connection = dbSetupRule.getSafeConnectionFromDifferentThread()) {
                    Transaction.performInOne(() -> {
                        try (Connection otherConnection = dbSetupRule.getSafeConnectionFromDifferentThread()) {
                            // Just opening two connections for pleasure :-)
                            Thread.sleep(50);
                            synchronized (monitorOfVerification) {
                                info(result, "DELETION PROCESS - In transaction");
                                info(result, "DELETION PROCESS - Waiting for verification");
                                monitorOfVerification.notifyAll();
                            }
                            synchronized (monitorOfDeletion) {
                                monitorOfDeletion.wait(500);
                            }
                            Thread.sleep(10);
                            synchronized (monitorOfVerification) {
                                assertThat(createDeleteFor("a_table").execute(), is(NB_ROW_AT_BEGINNING));
                                info(result, "DELETION PROCESS - Waiting for verification (lines deleted)");
                                monitorOfVerification.notifyAll();
                            }
                            synchronized (monitorOfDeletion) {
                                monitorOfDeletion.wait(500);
                            }
                            Thread.sleep(10);
                        }
                        return null;
                    });
                }
                assertThat(getTableLines(), hasSize(0));
                if (rollbackInTransaction) {
                    info(result, "DELETION PROCESS - Perform rollback");
                    throw new IllegalArgumentException();
                }
                return null;
            });
        } catch (Exception e) {
            info(result, "DELETION PROCESS - Rollback performed");
        }
        synchronized (monitorOfVerification) {
            info(result, "DELETION PROCESS - Transaction closed");
            monitorOfVerification.notifyAll();
        }
    });
    Thread deletionVerifications = new Thread(() -> {
        try {
            synchronized (monitorOfVerification) {
                monitorOfVerification.wait(500);
            }
            Thread.sleep(10);
            synchronized (monitorOfDeletion) {
                info(result, "VERIFICATION PROCESS - BEFORE DELETION - " + getTableLines().size() + " line(s)");
                monitorOfDeletion.notifyAll();
            }
            synchronized (monitorOfVerification) {
                monitorOfVerification.wait(500);
            }
            Thread.sleep(10);
            synchronized (monitorOfDeletion) {
                info(result, "VERIFICATION PROCESS - AFTER DELETION - " + getTableLines().size() + " line(s)");
                monitorOfDeletion.notifyAll();
            }
            synchronized (monitorOfVerification) {
                monitorOfVerification.wait(500);
            }
            Thread.sleep(10);
            synchronized (monitorOfDeletion) {
                info(result,
                        "VERIFICATION PROCESS - AFTER TRANSACTION - " + getTableLines().size() + " line(s)");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    List<Thread> threads = Arrays.asList(deletionVerifications, deletionProcess);
    for (Thread thread : threads) {
        thread.start();
    }
    for (Thread thread : threads) {
        thread.join(2000);
    }
    return result;
}