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:org.hyperledger.fabric.sdk.Peer.java

private boolean waitForInvokeComplete(final String txid) {
    int waitTime = this.chain.getInvokeWaitTime();
    logger.debug(String.format("waiting %d seconds before emitting invoke complete event", waitTime));

    final boolean[] invokeCompleted = { false };
    final Object lock = new Object();
    this.chain.getEventHub().registerTxEvent(txid, new TransactionListener() {
        @Override//w  w w  .java2s  . co  m
        public void process(Fabric.Transaction transaction) {
            chain.getEventHub().unregisterTxEvent(txid);
            invokeCompleted[0] = true;
            synchronized (lock) {
                lock.notify();
            }
        }
    });
    try {
        synchronized (lock) {
            lock.wait(waitTime * 1000);
        }
    } catch (InterruptedException e) {
        // ignore
    }
    return invokeCompleted[0];
}

From source file:org.hyperledger.fabric.sdk.Peer.java

private boolean waitForDeployComplete(final String txid) {
    int waitTime = this.chain.getDeployWaitTime();
    logger.debug(String.format("waiting %d seconds before emitting deploy complete event", waitTime));

    final boolean[] deployCompleted = { false };
    final Object lock = new Object();
    this.chain.getEventHub().registerTxEvent(txid, new TransactionListener() {
        @Override/*  w  w w . ja v  a2  s  . c  o  m*/
        public void process(Fabric.Transaction transaction) {
            chain.getEventHub().unregisterTxEvent(txid);
            deployCompleted[0] = true;
            synchronized (lock) {
                lock.notify();
            }
        }
    });

    try {
        synchronized (lock) {
            lock.wait(waitTime * 1000);
        }
    } catch (InterruptedException e) {
        // ignore
    }
    return deployCompleted[0];
}

From source file:com.aurel.track.admin.server.dbbackup.DatabaseBackupAction.java

/**
 * Start the backup background thread//from  w  ww .j  a va  2s.  c om
 * @return
 */
public String backup() {
    loadFirst = false;
    errors = new ArrayList<LabelValueBean>();
    ApplicationBean.getInstance().setBackupErrors(errors); // reset error list

    ApplicationBean appBean = ApplicationBean.getInstance();
    synchronized (appBean) {
        if (appBean.isBackupInProgress()) {
            errors.add(new LabelValueBean(getText("admin.server.databaseBackup.error.backupInProgress"), ""));
            backupSuccess = false;
            return createResponse();
        }
        appBean.setBackupInProgress(true);

        BackupThread backupThread;
        if (!sendNotifyEmail) {
            backupThread = new BackupThread(appBean, backupName, includeAttachments);
        } else {
            Locale locale = (Locale) session.get(Constants.LOCALE_KEY);
            TPersonBean person = (TPersonBean) session.get(Constants.USER_KEY);
            StringBuilder messageBody = new StringBuilder();
            messageBody.append(getText("admin.server.databaseBackup.lbl.backupSuccessfully"));
            messageBody.append("\n\n");
            messageBody.append(getText("admin.server.databaseBackup.lbl.backupName")).append(":");
            messageBody.append(" ").append(backupName).append(".zip").append("\n\n");
            messageBody.append(getText("admin.server.databaseBackup.lbl.includeAttachments")).append(":");
            messageBody.append(" ").append(includeAttachments).append("\n\n");

            backupThread = new BackupThread(appBean, backupName, includeAttachments, person, locale,
                    messageBody);
        }

        // Catch early errors
        Object monitor = new Object();
        try {
            new Thread(backupThread).start();
            boolean backupIsRunning = !backupThread.isDone();
            int i = 0;

            synchronized (monitor) {
                while (backupIsRunning && i < 5) {
                    ++i;
                    monitor.wait(1000);
                    backupIsRunning = !backupThread.isDone();
                }
            }
        } catch (InterruptedException ie) {
            LOGGER.error(ie.getMessage());
        }

        backupSuccess = ApplicationBean.getInstance().getBackupErrors() == null
                || ApplicationBean.getInstance().getBackupErrors().isEmpty();
        prepare();
        return createResponse();
    }
}

From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java

/**
 * Stop program execution for nn millis.
 * //w  w w  . j  a v  a  2 s .  c om
 * @param millis the number of millis-seconds to wait for, <code>0</code> stops program forever.
 */
private void waitFor(long millis) {
    Object lock = new Object();
    synchronized (lock) {
        try {
            lock.wait(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // good practice if don't throw
            getLog().warn("Spuriously interrupted while waiting for " + millis + "ms", e);
        }
    }
}

From source file:org.apache.beam.runners.flink.translation.wrappers.streaming.io.UnboundedSourceWrapper.java

@Override
public void run(SourceContext<WindowedValue<OutputT>> ctx) throws Exception {
    if (!(ctx instanceof StreamSource.ManualWatermarkContext)) {
        throw new RuntimeException("Cannot emit watermarks, this hints at a misconfiguration/bug.");
    }/*from  w w w.ja  va  2 s.  co  m*/

    context = (StreamSource.ManualWatermarkContext<WindowedValue<OutputT>>) ctx;

    if (localReaders.size() == 0) {
        // do nothing, but still look busy ...
        // also, output a Long.MAX_VALUE watermark since we know that we're not
        // going to emit anything
        // we can't return here since Flink requires that all operators stay up,
        // otherwise checkpointing would not work correctly anymore
        ctx.emitWatermark(new Watermark(Long.MAX_VALUE));

        // wait until this is canceled
        final Object waitLock = new Object();
        while (isRunning) {
            try {
                // Flink will interrupt us at some point
                //noinspection SynchronizationOnLocalVariableOrMethodParameter
                synchronized (waitLock) {
                    // don't wait indefinitely, in case something goes horribly wrong
                    waitLock.wait(1000);
                }
            } catch (InterruptedException e) {
                if (!isRunning) {
                    // restore the interrupted state, and fall through the loop
                    Thread.currentThread().interrupt();
                }
            }
        }
    } else if (localReaders.size() == 1) {
        // the easy case, we just read from one reader
        UnboundedSource.UnboundedReader<OutputT> reader = localReaders.get(0);

        boolean dataAvailable = reader.start();
        if (dataAvailable) {
            emitElement(ctx, reader);
        }

        setNextWatermarkTimer(this.runtimeContext);

        while (isRunning) {
            dataAvailable = reader.advance();

            if (dataAvailable) {
                emitElement(ctx, reader);
            } else {
                Thread.sleep(50);
            }
        }
    } else {
        // a bit more complicated, we are responsible for several localReaders
        // loop through them and sleep if none of them had any data

        int numReaders = localReaders.size();
        int currentReader = 0;

        // start each reader and emit data if immediately available
        for (UnboundedSource.UnboundedReader<OutputT> reader : localReaders) {
            boolean dataAvailable = reader.start();
            if (dataAvailable) {
                emitElement(ctx, reader);
            }
        }

        // a flag telling us whether any of the localReaders had data
        // if no reader had data, sleep for bit
        boolean hadData = false;
        while (isRunning) {
            UnboundedSource.UnboundedReader<OutputT> reader = localReaders.get(currentReader);
            boolean dataAvailable = reader.advance();

            if (dataAvailable) {
                emitElement(ctx, reader);
                hadData = true;
            }

            currentReader = (currentReader + 1) % numReaders;
            if (currentReader == 0 && !hadData) {
                Thread.sleep(50);
            } else if (currentReader == 0) {
                hadData = false;
            }
        }

    }
}

From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java

public List<DeviceAddress> queryAndClose(final Set<String> deviceIds) {
    try {// www  . java  2s.  com
        final Object lock = new Object();
        synchronized (lock) {
            eventBus.register(new Object() {
                @Subscribe
                public void handleMessageReceivedEvent(MessageReceivedEvent event) {
                    if (deviceIds.contains(event.getDeviceId())) {
                        synchronized (lock) {
                            lock.notify();
                        }
                    }
                }
            });
            startListener();
            sendAnnounceMessage();
            try {
                lock.wait(MAX_WAIT);
            } catch (InterruptedException ex) {
            }
            synchronized (localDiscoveryRecords) {
                return Lists.newArrayList(Iterables.concat(
                        Iterables.transform(deviceIds, Functions.forMap(localDiscoveryRecords.asMap()))));
            }
        }
    } finally {
        close();
    }
}

From source file:org.fabrician.enabler.DockerContainer.java

private void logDockerInspectMetadata(final String dockerContainerId) throws Exception {
    getEngineLogger().info(Strings.repeat("-", 10) + "inspect metadata for [" + dockerContainerId + "]"
            + Strings.repeat("-", 10));
    String command = "docker inspect " + dockerContainerId;
    if (useSudo) {
        command = "sudo " + command;
    }/*from ww  w .  ja v  a2 s  . c o m*/
    File workDir = new File(getWorkDir());
    ProcessWrapper p = null;
    try {
        String engineOS = getEngineProperty(EngineProperties.OS);
        p = getProcessWrapper(command, workDir, engineOS + "_inspect.pid");
        Object lock = p.getLock();
        p.exec();
        synchronized (lock) {
            try {
                if (p.isRunning()) {
                    lock.wait(3000); // 3 secs
                    if (p.isRunning()) {
                        p.destroy();
                    }
                }
            } catch (InterruptedException e) {
                getEngineLogger().warning("logDockerInspectMetadata() thread was interrupted");
            }
        }
    } catch (Exception ex) {
        getEngineLogger().log(Level.SEVERE, "while inspecting docker container [" + dockerContainerId + "]",
                ex);
    }
}

From source file:com.rapleaf.hank.ZkTestCase.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARN);

    setupZkServer();//w  w  w. ja  va2  s .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);
    createNodeRecursively(zkRoot);
}

From source file:org.fabrician.enabler.DockerContainer.java

private void buildDockerImage() throws Exception {
    getEngineLogger()//from  ww  w . j a v a2  s  .  co m
            .info(Strings.repeat("-", 10) + "building [" + dockerImage + "]" + Strings.repeat("-", 10));
    // check if we should reuse existing image?
    boolean reuse_image = resolveToBoolean(REUSE_IMAGE_VAR);
    boolean image_exist = dockerClient().isImageExist(dockerImage);
    if (reuse_image) {
        if (image_exist) {
            getEngineLogger().info("Existing docker image [" + dockerImage + "] exists and will be reused.");
            return;
        }
    } else {
        // delete existing image before build
        if (image_exist) {
            getEngineLogger().info("Deleting existing docker image [" + dockerImage + "] before build.");
            dockerClient().deleteImageByTag(dockerImage);
        }
    }
    // check if Docker file exits?
    File dockerContextDir = resolveToFile(DOCKER_CONTEXT_DIR_VAR);
    File dockerFile = new File(dockerContextDir, "Dockerfile");
    Validate.isTrue(dockerFile.exists(),
            "Required Dockerfile for build does not exist at path [" + dockerFile.getCanonicalPath() + "]");
    // construct build options
    String command = "docker build " + BuildCmdOptions.buildAll(getRuntimeContext()) + " -t " + dockerImage
            + " . ";
    if (useSudo) {
        command = "sudo " + command;
    }
    getEngineLogger().info(Strings.repeat("-", 10) + " begin build command " + Strings.repeat("-", 10));
    getEngineLogger().info(command);
    getEngineLogger().info(Strings.repeat("-", 10) + " end build command " + Strings.repeat("-", 10));
    ProcessWrapper p = null;
    int build_timeout = resolveToInteger(BUILD_TIMEOUT_VAR);// in secs
    try {
        String engineOS = getEngineProperty(EngineProperties.OS);
        p = getProcessWrapper(command, dockerContextDir, engineOS + "_build.pid");
        Object lock = p.getLock();
        p.exec();
        synchronized (lock) {
            try {
                if (p.isRunning()) {
                    lock.wait(build_timeout * 1000);
                    if (p.isRunning()) {
                        p.destroy();
                    }
                }
            } catch (InterruptedException e) {
                getEngineLogger().warning("buildDockerImage() thread was interrupted");
            }
        }
    } catch (Exception ex) {
        getEngineLogger().log(Level.SEVERE, "while building docker image [" + dockerImage + "]", ex);
        throw ex;
    }
    // check for image

    image_exist = dockerClient().isImageExist(dockerImage);
    if (!image_exist) {
        throw new Exception("Build failed for image [" + dockerImage + "]");
    } else {
        getEngineLogger().info("Build succeeded for image [" + dockerImage + "]");
    }
}

From source file:com.alibaba.napoli.gecko.service.impl.DefaultRemotingClient.java

public void awaitReadyInterrupt(final String group, final long time)
        throws NotifyRemotingException, InterruptedException {
    if (StringUtils.isBlank(group)) {
        throw new IllegalArgumentException("Blank group");
    }// ww w  .j  av a 2 s .c  o 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 + "");
                }
            }
        }
    }

}