Example usage for java.lang Runnable wait

List of usage examples for java.lang Runnable wait

Introduction

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

Prototype

public final void wait() throws InterruptedException 

Source Link

Document

Causes the current thread to wait until it is awakened, typically by being notified or interrupted.

Usage

From source file:com.rareventure.gps2.GTG.java

/**
 * A hack to prevent gps and caches from being accessed when we are making
 * major changes. Locks all the caches in a newly created thread and doesn't
 * let go. In general if a change was made, killSelf() may
 * prove useful./*from   w w  w.  j  av  a 2 s . c om*/
 */
public static void lockGpsCaches(final Runnable myRunnable) {
    final boolean[] ready = new boolean[1];

    Runnable r = new Runnable() {

        @Override
        public void run() {
            synchronized (apCache) {
                synchronized (ttCache) {
                    synchronized (gpsLocCache) {
                        synchronized (this) {
                            ready[0] = true;
                            notify();

                        }

                        if (myRunnable != null)
                            myRunnable.run();

                        synchronized (this) {
                            try {
                                this.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
            }
        }
    };

    new Thread(r).start();

    synchronized (r) {
        while (!ready[0])
            try {
                r.wait();
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
    }
}

From source file:org.eclipse.che.plugin.docker.client.DockerConnector.java

protected void doPull(String image, String tag, String registry, final ProgressMonitor progressMonitor,
        URI dockerDaemonUri) throws IOException, InterruptedException {
    final List<Pair<String, ?>> headers = new ArrayList<>(3);
    headers.add(Pair.of("Content-Type", MediaType.TEXT_PLAIN));
    headers.add(Pair.of("Content-Length", 0));
    headers.add(Pair.of("X-Registry-Auth", initialAuthConfig.getAuthConfigHeader()));

    try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("POST")
            .path("/images/create").query("fromImage", registry != null ? registry + "/" + image : image)
            .headers(headers)) {/*from  www  .  j a  v a2s  . c o  m*/
        if (tag != null) {
            connection.query("tag", tag);
        }
        final DockerResponse response = connection.request();
        final int status = response.getStatus();
        if (OK.getStatusCode() != status) {
            throw getDockerException(response);
        }
        try (InputStream responseStream = response.getInputStream()) {
            JsonMessageReader<ProgressStatus> progressReader = new JsonMessageReader<>(responseStream,
                    ProgressStatus.class);

            final ValueHolder<IOException> errorHolder = new ValueHolder<>();
            // Here do some trick to be able interrupt pull process. Basically for now it is not possible interrupt docker daemon while
            // it's pulling images but here we need just be able to close connection to the unix socket. Thread is blocking while read
            // from the socket stream so need one more thread that is able to close socket. In this way we can release thread that is
            // blocking on i/o.
            final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        ProgressStatus progressStatus;
                        while ((progressStatus = progressReader.next()) != null) {
                            progressMonitor.updateProgress(progressStatus);
                        }
                    } catch (IOException e) {
                        errorHolder.set(e);
                    }
                    synchronized (this) {
                        notify();
                    }
                }
            };
            executor.execute(runnable);
            // noinspection SynchronizationOnLocalVariableOrMethodParameter
            synchronized (runnable) {
                runnable.wait();
            }
            final IOException ioe = errorHolder.get();
            if (ioe != null) {
                throw ioe;
            }
        }
    }
}

From source file:org.eclipse.che.plugin.docker.client.DockerConnector.java

/**
 * Builds new docker image from specified tar archive that must contain Dockerfile.
 *
 * @param repository/*from   ww  w.j av a  2 s.  c om*/
 *         full repository name to be applied to newly created image
 * @param tar
 *         archived files that are needed for creation docker images (e.g. file of directories used in ADD instruction in Dockerfile).
 *         One of them must be Dockerfile.
 * @param progressMonitor
 *         ProgressMonitor for images creation process
 * @param dockerDaemonUri
 *         Uri for remote access to docker API
 * @param authConfigs
 *         Authentication configuration for private registries. Can be null.
 * @param memoryLimit
 *         Memory limit for build in bytes
 * @param memorySwapLimit
 *         Total memory in bytes (memory + swap), -1 to enable unlimited swap
 * @return image id
 * @throws IOException
 * @throws InterruptedException
 *         if build process was interrupted
 */
protected String doBuildImage(String repository, File tar, final ProgressMonitor progressMonitor,
        URI dockerDaemonUri, AuthConfigs authConfigs, boolean doForcePull, long memoryLimit,
        long memorySwapLimit) throws IOException, InterruptedException {
    if (authConfigs == null) {
        authConfigs = initialAuthConfig.getAuthConfigs();
    }
    final List<Pair<String, ?>> headers = new ArrayList<>(3);
    headers.add(Pair.of("Content-Type", "application/x-compressed-tar"));
    headers.add(Pair.of("Content-Length", tar.length()));
    headers.add(
            Pair.of("X-Registry-Config", Base64.encodeBase64String(JsonHelper.toJson(authConfigs).getBytes())));

    try (InputStream tarInput = new FileInputStream(tar);
            DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("POST")
                    .path("/build").query("rm", 1).query("forcerm", 1).query("pull", doForcePull)
                    .headers(headers).entity(tarInput)) {
        if (repository != null) {
            connection.query("t", repository);
        }
        if (memoryLimit != 0) {
            connection.query("memory", memoryLimit);
        }
        if (memorySwapLimit != 0) {
            connection.query("memswap", memorySwapLimit);
        }
        final DockerResponse response = connection.request();
        final int status = response.getStatus();
        if (OK.getStatusCode() != status) {
            throw getDockerException(response);
        }
        try (InputStream responseStream = response.getInputStream()) {
            JsonMessageReader<ProgressStatus> progressReader = new JsonMessageReader<>(responseStream,
                    ProgressStatus.class);

            final ValueHolder<IOException> errorHolder = new ValueHolder<>();
            final ValueHolder<String> imageIdHolder = new ValueHolder<>();
            // Here do some trick to be able interrupt build process. Basically for now it is not possible interrupt docker daemon while
            // it's building images but here we need just be able to close connection to the unix socket. Thread is blocking while read
            // from the socket stream so need one more thread that is able to close socket. In this way we can release thread that is
            // blocking on i/o.
            final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        ProgressStatus progressStatus;
                        while ((progressStatus = progressReader.next()) != null) {
                            final String buildImageId = getBuildImageId(progressStatus);
                            if (buildImageId != null) {
                                imageIdHolder.set(buildImageId);
                            }
                            progressMonitor.updateProgress(progressStatus);
                        }
                    } catch (IOException e) {
                        errorHolder.set(e);
                    }
                    synchronized (this) {
                        notify();
                    }
                }
            };
            executor.execute(runnable);
            // noinspection SynchronizationOnLocalVariableOrMethodParameter
            synchronized (runnable) {
                runnable.wait();
            }
            final IOException ioe = errorHolder.get();
            if (ioe != null) {
                throw ioe;
            }
            if (imageIdHolder.get() == null) {
                throw new IOException("Docker image build failed");
            }
            return imageIdHolder.get();
        }
    }
}

From source file:de.tum.frm2.nicos_android.gui.MainActivity.java

private void on_client_connected() {
    // Query moveables.
    final ArrayList lowercaseMoveables = (ArrayList) NicosClient.getClient()
            .getDeviceList("nicos.core.device.Moveable", true, null, null);

    // Ask for current daemon status.
    Object untyped_state = NicosClient.getClient().ask("getstatus", null);
    if (untyped_state == null) {
        return;//www .  j a  v a  2  s . c  o  m
    }
    final HashMap state = (HashMap) untyped_state;
    Object[] statusTuple = (Object[]) state.get("status");
    _current_status = (int) statusTuple[0];

    // Fill _moveables.
    Runnable uiAddMoveables = new Runnable() {
        @Override
        public void run() {
            synchronized (this) {
                // Filter device list for moveables.
                ArrayList devlist = (ArrayList) state.get("devices");
                for (Object deviceObject : devlist) {
                    String device = (String) deviceObject;
                    String cachekey = device.toLowerCase();
                    if (!lowercaseMoveables.contains(cachekey)) {
                        continue;
                    }
                    // Create device and add it.
                    Device moveable = new Device(device, cachekey);
                    _moveables.add(moveable);

                }

                // Sort devices in place.
                Collections.sort(_moveables, new Comparator<Device>() {
                    @Override
                    public int compare(Device lhs, Device rhs) {
                        return lhs.getCacheName().compareTo(rhs.getCacheName());
                    }
                });
                notify();
            }
        }
    };

    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (uiAddMoveables) {
        _uiThread.post(uiAddMoveables);
        try {
            uiAddMoveables.wait();
        } catch (InterruptedException e) {
            return;
        }
    }

    // Query parameters.
    for (final Device device : _moveables) {
        final ArrayList params = NicosClient.getClient().getDeviceParams(device.getCacheName());
        if (params == null) {
            continue;
        }

        // Add params to device.
        Runnable uiAddParams = new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    for (Object param : params) {
                        Object[] tuple = (Object[]) param;
                        // Split device name from parameter name.
                        // e.g. t/fmtstr -> fmtstr
                        String[] keyParts = ((String) tuple[0]).split(("/"));
                        device.addParam(keyParts[1], tuple[1]);
                    }
                    notify();
                }
            }
        };

        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (uiAddParams) {
            _uiThread.post(uiAddParams);
            try {
                uiAddParams.wait();
            } catch (InterruptedException e) {
                return;
            }
        }
    }

    // Remove all moveables without abslimits.
    Runnable uiRemoveDevicesWithoutLimits = new Runnable() {
        @Override
        public void run() {
            synchronized (this) {
                Iterator<Device> it = _moveables.iterator();
                while (it.hasNext()) {
                    Device device = it.next();
                    if (device.getParam("abslimits") == null) {
                        it.remove();
                    }
                }
                _devicesAdapter.notifyDataSetChanged();
                _canAccessDevices = true;
                notify();
            }
        }
    };

    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (uiRemoveDevicesWithoutLimits) {
        _uiThread.post(uiRemoveDevicesWithoutLimits);
        try {
            uiRemoveDevicesWithoutLimits.wait();
        } catch (InterruptedException e) {
            return;
        }
    }

    // Query statuses and values of all devices.
    for (final Device device : _moveables) {
        // Query this device's status.
        Object untypedStatus = NicosClient.getClient().getDeviceStatus(device.getName());
        Object[] tupleStatus;

        try {
            tupleStatus = (Object[]) untypedStatus;
            if (tupleStatus == null) {
                throw new RuntimeException();
            }
        } catch (Exception e) {
            tupleStatus = new Object[] { -1, null };
        }

        final int status = (int) tupleStatus[0];
        final Object value = NicosClient.getClient().getDeviceValue(device.getName());

        // Query value types.
        Object valuetype = NicosClient.getClient().getDeviceValuetype(device.getName());
        String pyclass;
        final Class valueclass;

        if (valuetype == null) {
            // Response timed out
            continue;
        }
        if (valuetype.getClass() == ClassDictConstructor.class) {
            // Java .o
            Object[] o = {};
            ClassDict s = ((ClassDict) ((ClassDictConstructor) valuetype).construct(o));
            s.__setstate__(new HashMap<String, Object>());
            pyclass = (String) s.get("__class__");
        } else {
            pyclass = (String) ((ClassDict) valuetype).get("__class__");
        }

        switch (pyclass) {
        case "__builtin__.float":
            valueclass = Double.class;
            break;
        case "__builtin__.double":
            valueclass = Double.class;
            break;
        case "nicos.core.params.tupleof":
            valueclass = Object[].class;
            break;
        case "nicos.core.params.oneof":
            valueclass = String.class;
            break;
        case "nicos.core.params.oneofdict":
            valueclass = String.class;
            break;
        case "nicos.core.params.limits":
            valueclass = Object[].class;
            break;
        default:
            valueclass = String.class;
            break;
        }

        // A runnable to update the device in UI thread with new status + value.
        Runnable uiChangeValue = new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    device.setStatus(status);
                    device.setValue(value);
                    device.setValuetype(valueclass);
                    _devicesAdapter.notifyDataSetChanged();
                    if (_currentDevice == device) {
                        _currentDeviceValueTextView.setText(device.getFormattedValue());
                    }
                    notify();
                }
            }
        };

        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (uiChangeValue) {
            _uiThread.post(uiChangeValue);
            try {
                uiChangeValue.wait();
            } catch (InterruptedException e) {
                return;
            }
        }
    }
}

From source file:org.eclipse.che.plugin.docker.client.DockerConnector.java

protected String doPush(final String repository, final String tag, final String registry,
        final ProgressMonitor progressMonitor, final URI dockerDaemonUri)
        throws IOException, InterruptedException {
    final List<Pair<String, ?>> headers = new ArrayList<>(3);
    headers.add(Pair.of("Content-Type", MediaType.TEXT_PLAIN));
    headers.add(Pair.of("Content-Length", 0));
    headers.add(Pair.of("X-Registry-Auth", initialAuthConfig.getAuthConfigHeader()));
    final String fullRepo = registry != null ? registry + "/" + repository : repository;
    final ValueHolder<String> digestHolder = new ValueHolder<>();

    try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("POST")
            .path("/images/" + fullRepo + "/push").headers(headers)) {
        if (tag != null) {
            connection.query("tag", tag);
        }//from w  w w .  j  a va  2 s .c  o  m
        final DockerResponse response = connection.request();
        final int status = response.getStatus();
        if (OK.getStatusCode() != status) {
            throw getDockerException(response);
        }
        try (InputStream responseStream = response.getInputStream()) {
            JsonMessageReader<ProgressStatus> progressReader = new JsonMessageReader<>(responseStream,
                    ProgressStatus.class);

            final ValueHolder<IOException> errorHolder = new ValueHolder<>();
            //it is necessary to track errors during the push, this is useful in the case when docker API returns status 200 OK,
            //but in fact we have an error (e.g docker registry is not accessible but we are trying to push).
            final ValueHolder<String> exceptionHolder = new ValueHolder<>();
            // Here do some trick to be able interrupt push process. Basically for now it is not possible interrupt docker daemon while
            // it's pushing images but here we need just be able to close connection to the unix socket. Thread is blocking while read
            // from the socket stream so need one more thread that is able to close socket. In this way we can release thread that is
            // blocking on i/o.
            final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        String digestPrefix = firstNonNull(tag, "latest") + ": digest: ";
                        ProgressStatus progressStatus;
                        while ((progressStatus = progressReader.next()) != null
                                && exceptionHolder.get() == null) {
                            progressMonitor.updateProgress(progressStatus);
                            if (progressStatus.getError() != null) {
                                exceptionHolder.set(progressStatus.getError());
                            }
                            String status = progressStatus.getStatus();
                            // Here we find string with digest which has following format:
                            // <tag>: digest: <digest> size: <size>
                            // for example:
                            // latest: digest: sha256:9a70e6222ded459fde37c56af23887467c512628eb8e78c901f3390e49a800a0 size: 62189
                            if (status != null && status.startsWith(digestPrefix)) {
                                String digest = status.substring(digestPrefix.length(),
                                        status.indexOf(" ", digestPrefix.length()));
                                digestHolder.set(digest);
                            }
                        }
                    } catch (IOException e) {
                        errorHolder.set(e);
                    }
                    synchronized (this) {
                        notify();
                    }
                }
            };
            executor.execute(runnable);
            // noinspection SynchronizationOnLocalVariableOrMethodParameter
            synchronized (runnable) {
                runnable.wait();
            }
            if (exceptionHolder.get() != null) {
                throw new DockerException(exceptionHolder.get(), 500);
            }
            if (digestHolder.get() == null) {
                LOG.error("Docker image {}:{} was successfully pushed, but its digest wasn't obtained",
                        fullRepo, firstNonNull(tag, "latest"));
                throw new DockerException(
                        "Docker image was successfully pushed, but its digest wasn't obtained", 500);
            }
            final IOException ioe = errorHolder.get();
            if (ioe != null) {
                throw ioe;
            }
        }
    }
    return digestHolder.get();
}