Example usage for com.google.common.util.concurrent SettableFuture isDone

List of usage examples for com.google.common.util.concurrent SettableFuture isDone

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SettableFuture isDone.

Prototype

@Override
    public boolean isDone() 

Source Link

Usage

From source file:com.google.gapid.server.GapitPkgInfoProcess.java

@Override
protected OutputHandler<PkgInfo.PackageList> createStdoutHandler() {
    return new BinaryHandler<PkgInfo.PackageList>(in -> {
        byte[] data = ByteStreams.toByteArray(in);
        return (data.length == 0) ? null : PkgInfo.PackageList.parseFrom(data);
    }) {//from   w  w w .  j  a  v a 2s .  c o  m
        @Override
        public void finish(SettableFuture<PackageList> result) throws InterruptedException {
            if (!result.isDone()) {
                result.setException(new Exception("The gapit command didn't produce any output!"));
            }
        }
    };
}

From source file:com.google.gapid.server.GapitPkgInfoProcess.java

@Override
protected OutputHandler<PackageList> createStderrHandler() {
    StringBuilder output = new StringBuilder();
    return new LoggingStringHandler<PackageList>(LOG, name, true, (line) -> {
        output.append(line).append('\n');
        return null;
    }) {/*from   ww  w. j  a v a  2s .c o m*/
        @Override
        public void finish(SettableFuture<PackageList> result) throws InterruptedException {
            if (!result.isDone() && output.length() > 0) {
                result.setException(new Exception("The gapit command failed:\n" + output.toString()));
            }
        }
    };
}

From source file:org.pentaho.caching.impl.PentahoCacheManagerFactory.java

public synchronized void unregisterProvider(String providerId, PentahoCacheProvidingService provider) {
    Set<ListenableFuture<PentahoCacheProvidingService>> invalidFutures = Sets.newHashSet();
    for (Iterator<SettableFuture<PentahoCacheProvidingService>> iterator = providerMap.get(providerId)
            .iterator(); iterator.hasNext();) {
        SettableFuture<PentahoCacheProvidingService> future = iterator.next();
        try {//www  .  jav a2s  .c  o m
            if (future.isDone() && future.get(10, TimeUnit.SECONDS).equals(provider)) {
                iterator.remove();
                invalidFutures.add(future);
            }
        } catch (Throwable t) {
            Logger.getLogger(providerId).log(Level.WARNING, "Unexpected exception", t);
        }
    }

    Set<String> pidSet = Sets.newHashSet();
    Iterator<RegistrationHandler> registrations = registrationHandlerMap.values().iterator();
    while (!invalidFutures.isEmpty() && registrations.hasNext()) {
        RegistrationHandler registrationHandler = registrations.next();
        if (invalidFutures.contains(registrationHandler.serviceFuture)) {
            pidSet.add(registrationHandler.pid);
        }
    }

    for (String pid : pidSet) {
        restartService(pid, providerId);
    }
}

From source file:com.codeabovelab.dm.cluman.cluster.docker.management.ProcessEventProcessor.java

@Override
public void processResponseStream(StreamContext<ProcessEvent> context) {
    Consumer<ProcessEvent> watcher = context.getWatcher();
    InputStream response = context.getStream();
    SettableFuture<Boolean> interrupter = context.getInterrupter();
    interrupter.addListener(() -> Thread.currentThread().interrupt(), MoreExecutors.directExecutor());
    try (FrameReader frameReader = new FrameReader(response)) {

        Frame frame = frameReader.readFrame();
        while (frame != null && !interrupter.isDone()) {
            try {
                ProcessEvent.watchRaw(watcher, frame.getMessage(), false);
            } catch (Exception e) {
                LOG.error("Cannot read body", e);
            } finally {
                frame = frameReader.readFrame();
            }/* w  w  w  . ja v a  2s. c o m*/
        }
    } catch (Exception t) {
        LOG.error("Cannot close reader", t);
    }

}

From source file:org.apache.beam.sdk.runners.inprocess.InProcessSideInputContainer.java

/**
 * Set the value of the {@link PCollectionView} in the {@link BoundedWindow} to be based on the
 * specified values, if the values are part of a later pane than currently exist within the
 * {@link PCollectionViewWindow}.//from  ww  w  . j  ava 2  s. co m
 */
private void updatePCollectionViewWindowValues(PCollectionView<?> view, BoundedWindow window,
        Collection<WindowedValue<?>> windowValues) {
    PCollectionViewWindow<?> windowedView = PCollectionViewWindow.of(view, window);
    SettableFuture<Iterable<? extends WindowedValue<?>>> future = null;
    try {
        future = viewByWindows.get(windowedView);
        if (future.isDone()) {
            Iterator<? extends WindowedValue<?>> existingValues = future.get().iterator();
            PaneInfo newPane = windowValues.iterator().next().getPane();
            // The current value may have no elements, if no elements were produced for the window,
            // but we are recieving late data.
            if (!existingValues.hasNext() || newPane.getIndex() > existingValues.next().getPane().getIndex()) {
                viewByWindows.invalidate(windowedView);
                viewByWindows.get(windowedView).set(windowValues);
            }
        } else {
            future.set(windowValues);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        if (future != null && !future.isDone()) {
            future.set(Collections.<WindowedValue<?>>emptyList());
        }
    } catch (ExecutionException e) {
        Throwables.propagate(e.getCause());
    }
}

From source file:com.vmware.photon.controller.common.thrift.BasicClientPool.java

@Override
public synchronized ListenableFuture<C> acquire() {
    if (promises.size() < options.getMaxWaiters()) {
        SettableFuture<C> future = SettableFuture.create();
        Promise<C> promise = new Promise<>(future);
        promises.add(promise);//from  w  w  w. j av  a2  s.  c o  m
        processPromises();
        if (options.getTimeoutMs() > 0 && !future.isDone()) {
            setTimeout(promise);
        }
        return future;
    }

    return Futures.immediateFailedFuture(new ClientPoolException("Too many waiters"));
}

From source file:com.facebook.presto.operator.OperatorContext.java

public void reserveMemory(long bytes) {
    ListenableFuture<?> future = driverContext.reserveMemory(bytes);
    if (!future.isDone()) {
        SettableFuture<?> currentMemoryFuture = memoryFuture.get();
        while (currentMemoryFuture.isDone()) {
            SettableFuture<?> settableFuture = SettableFuture.create();
            // We can't replace one that's not done, because the task may be blocked on that future
            if (memoryFuture.compareAndSet(currentMemoryFuture, settableFuture)) {
                currentMemoryFuture = settableFuture;
            } else {
                currentMemoryFuture = memoryFuture.get();
            }/*w ww. j  a v a 2  s .  c  o m*/
        }

        SettableFuture<?> finalMemoryFuture = currentMemoryFuture;
        // Create a new future, so that this operator can un-block before the pool does, if it's moved to a new pool
        Futures.addCallback(future, new FutureCallback<Object>() {
            @Override
            public void onSuccess(Object result) {
                finalMemoryFuture.set(null);
            }

            @Override
            public void onFailure(Throwable t) {
                finalMemoryFuture.set(null);
            }
        });
    }
    long newReservation = memoryReservation.addAndGet(bytes);
    if (newReservation > maxMemoryReservation) {
        memoryReservation.getAndAdd(-bytes);
        throw exceededLocalLimit(new DataSize(maxMemoryReservation, BYTE));
    }
}

From source file:com.codeabovelab.dm.cluman.cluster.docker.management.JsonStreamProcessor.java

@Override
public void processResponseStream(StreamContext<T> context) {
    Consumer<T> watcher = context.getWatcher();
    InputStream response = context.getStream();
    final Thread thread = Thread.currentThread();
    SettableFuture<Boolean> interrupter = context.getInterrupter();
    interrupter.addListener(() -> thread.interrupt(), MoreExecutors.directExecutor());
    try {/*from w ww  . j a  v a 2 s .c  o m*/
        JsonParser jp = JSON_FACTORY.createParser(response);
        Boolean closed = jp.isClosed();
        JsonToken nextToken = jp.nextToken();
        while (!closed && nextToken != null && nextToken != JsonToken.END_OBJECT && !interrupter.isDone()) {
            try {
                ObjectNode objectNode = OBJECT_MAPPER.readTree(jp);
                // exclude empty item serialization into class #461
                if (!objectNode.isEmpty(null)) {
                    T next = OBJECT_MAPPER.treeToValue(objectNode, clazz);
                    LOG.trace("Monitor value: {}", next);
                    watcher.accept(next);
                }
            } catch (Exception e) {
            }

            closed = jp.isClosed();
            nextToken = jp.nextToken();
        }
    } catch (Throwable t) {
        throw Throwables.asRuntime(t);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            LOG.error("Can't close stream", e);

        }
    }

}

From source file:com.google.cloud.dataflow.sdk.util.state.WindmillStateReader.java

private <T> void consumeTagValue(TagValue tagValue, StateTag stateTag) {
    @SuppressWarnings("unchecked")
    SettableFuture<T> future = (SettableFuture<T>) futures.get(stateTag);
    if (future == null) {
        throw new IllegalStateException("Missing future for " + stateTag);
    } else if (future.isDone()) {
        LOG.error("Future for {} is already done", stateTag);
    }/*from   w w w  . java2  s .  c  o  m*/

    @SuppressWarnings("unchecked")
    Coder<T> coder = (Coder<T>) coders.remove(stateTag);
    if (coder == null) {
        throw new IllegalStateException("Missing coder for " + stateTag);
    }

    if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) {
        InputStream inputStream = tagValue.getValue().getData().newInput();
        try {
            T value = coder.decode(inputStream, Coder.Context.OUTER);
            future.set(value);
        } catch (IOException e) {
            throw new IllegalStateException("Unable to decode value using " + coder, e);
        }
    } else {
        future.set(null);
    }
}

From source file:com.google.cloud.dataflow.sdk.util.state.WindmillStateReader.java

private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) {
    @SuppressWarnings("unchecked")
    SettableFuture<Instant> future = (SettableFuture<Instant>) futures.get(stateTag);
    if (future == null) {
        throw new IllegalStateException("Missing future for " + stateTag);
    } else if (future.isDone()) {
        LOG.error("Future for {} is already done", stateTag);
    }/*from  ww w  .  j  a v a2s .  c o  m*/

    Instant hold = null;
    for (long timestamp : watermarkHold.getTimestampsList()) {
        Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp));
        if (hold == null || instant.isBefore(hold)) {
            hold = instant;
        }
    }

    future.set(hold);
}