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

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

Introduction

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

Prototype

boolean isDone();

Source Link

Document

Returns true if this task completed.

Usage

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();
            }//from ww  w  .  j a v a2 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:org.ikasan.flow.visitorPattern.invoker.ConcurrentSplitterFlowElementInvoker.java

@Override
public FlowElement invoke(FlowEventListener flowEventListener, String moduleName, String flowName,
        final FlowInvocationContext flowInvocationContext, FlowEvent flowEvent,
        FlowElement<Splitter> flowElement) {
    flowInvocationContext.addInvokedComponentName(flowElement.getComponentName());
    notifyListenersBeforeElement(flowEventListener, moduleName, flowName, flowEvent, flowElement);

    Splitter splitter = flowElement.getFlowComponent();
    List payloads;/*w w  w  .  ja  v a  2s.  c  om*/
    if (requiresFullEventForInvocation == null) {
        try {
            // try with flowEvent and if successful mark this component
            payloads = splitter.split(flowEvent);
            requiresFullEventForInvocation = Boolean.TRUE;
        } catch (ClassCastException e) {
            payloads = splitter.split(flowEvent.getPayload());
            requiresFullEventForInvocation = Boolean.FALSE;
        }
    } else {
        if (requiresFullEventForInvocation.booleanValue()) {
            payloads = splitter.split(flowEvent);
        } else {
            payloads = splitter.split(flowEvent.getPayload());
        }
    }

    FlowElement nextFlowElement = getDefaultTransition(flowElement);
    if (nextFlowElement == null) {
        throw new InvalidFlowException("FlowElement [" + flowElement.getComponentName()
                + "] contains a Splitter, but it has no default transition! "
                + "Splitters should never be the last component in a flow");
    }

    if (payloads == null || payloads.size() == 0) {
        throw new SplitterException("FlowElement [" + flowElement.getComponentName() + "] contains a Splitter. "
                + "Splitters must return at least one payload.");
    }

    // initialise futures task stats
    count = new AtomicInteger(0);
    callbackException = null;

    List<ListenableFuture<FlowInvocationContext>> futures = new ArrayList<ListenableFuture<FlowInvocationContext>>(
            payloads.size());
    for (Object payload : payloads) {
        if (payload instanceof FlowEvent) {
            flowEvent = (FlowEvent) payload;
        } else {
            flowEvent.setPayload(payload);
        }
        notifyListenersAfterElement(flowEventListener, moduleName, flowName, flowEvent, flowElement);

        FlowElement nextFlowElementInRoute = nextFlowElement;

        // TODO - replace new DefaultFlowInvocationContext with a factory method
        FlowInvocationContext asyncTaskFlowInvocationContext = new DefaultFlowInvocationContext();
        asyncTaskFlowInvocationContext.combine(flowInvocationContext);
        Callable<FlowInvocationContext> asyncTask = newAsyncTask(nextFlowElementInRoute, flowEventListener,
                moduleName, flowName, asyncTaskFlowInvocationContext, flowEvent);
        final ListenableFuture<FlowInvocationContext> listenableFuture = executorService.submit(asyncTask);
        futures.add(listenableFuture);
        Futures.addCallback(listenableFuture, new FutureCallback<FlowInvocationContext>() {
            public void onSuccess(FlowInvocationContext taskFlowInvocationContext) {
                count.addAndGet(1);
            }

            public void onFailure(Throwable thrown) {
                synchronized (callbackException) {
                    if (callbackException == null) {
                        if (thrown instanceof SplitFlowElementException) {
                            SplitFlowElementException splitFlowElementException = (SplitFlowElementException) thrown;
                            callbackException = splitFlowElementException.getThrown();
                            failedTaskFlowInvocationContext = splitFlowElementException
                                    .getFlowInvocationContext();
                        } else {
                            callbackException = thrown;
                        }
                    }
                }
            }
        });

        if (callbackException != null) {
            break;
        }
    }

    while (pendingCallback(payloads)) {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            logger.warn("Sleep interrupted", e);
        }
    }

    if (callbackException != null) {
        for (ListenableFuture future : futures) {
            try {
                if (!future.isDone()) {
                    future.cancel(true);
                }
            } catch (CancellationException e) {
                logger.warn("Failed to cancel task", e);
            }
        }

        flowInvocationContext.combine(failedTaskFlowInvocationContext);
        if (callbackException instanceof RuntimeException) {
            throw (RuntimeException) callbackException;
        }

        throw new SplitterException(callbackException);
    }

    return null;
}

From source file:com.facebook.presto.memory.LegacyQueryContext.java

private synchronized boolean tryUpdateUserMemory(String allocationTag, long delta) {
    if (delta <= 0) {
        ListenableFuture<?> future = updateUserMemory(allocationTag, delta);
        // When delta == 0 and the pool is full the future can still not be done,
        // but, for negative deltas it must always be done.
        if (delta < 0) {
            verify(future.isDone(), "future should be done");
        }//w  ww  .  j a  v  a  2s .  co  m
        return true;
    }
    if (queryMemoryContext.getUserMemory() + delta > maxMemory) {
        return false;
    }
    return memoryPool.tryReserve(queryId, allocationTag, delta);
}

From source file:org.jenkinsci.plugins.workflow.support.concurrent.ListFuture.java

/**
 * Calls the get method of all dependency futures to work around a bug in
 * some ListenableFutures where the listeners aren't called until get() is
 * called.//from www .j  a  v  a 2  s .  c o m
 */
private void callAllGets() throws InterruptedException {
    List<? extends ListenableFuture<? extends V>> oldFutures = futures;
    if (oldFutures != null && !isDone()) {
        for (ListenableFuture<? extends V> future : oldFutures) {
            // We wait for a little while for the future, but if it's not done,
            // we check that no other futures caused a cancellation or failure.
            // This can introduce a delay of up to 10ms in reporting an exception.
            while (!future.isDone()) {
                try {
                    future.get();
                } catch (Error e) {
                    throw e;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Throwable e) {
                    // ExecutionException / CancellationException / RuntimeException
                    if (allMustSucceed) {
                        return;
                    } else {
                        continue;
                    }
                }
            }
        }
    }
}

From source file:com.kylinolap.storage.hbase.ConcurrentHBaseTupleIterator.java

private void cancalScanTasks() {
    for (ListenableFuture<Long> scanFuture : scanFutures) {
        if (!scanFuture.isDone()) {
            try {
                scanFuture.cancel(true);
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e);
            }/*from  w  w  w. j av a 2s.  c  om*/
        }
    }
}

From source file:com.facebook.presto.memory.DefaultQueryContext.java

private synchronized boolean tryUpdateUserMemory(String allocationTag, long delta) {
    if (delta <= 0) {
        ListenableFuture<?> future = updateUserMemory(allocationTag, delta);
        // When delta == 0 and the pool is full the future can still not be done,
        // but, for negative deltas it must always be done.
        if (delta < 0) {
            verify(future.isDone(), "future should be done");
        }//from   w  ww . j  a v a  2s.  co m
        return true;
    }
    if (queryMemoryContext.getUserMemory() + delta > maxUserMemory) {
        return false;
    }
    return memoryPool.tryReserve(queryId, allocationTag, delta);
}

From source file:com.facebook.buck.distributed.MaterializerDummyFileHashCache.java

private void printMissingFiles() {
    for (BuildJobStateFileHashEntry fileEntry : fileMaterializationFuturesByFileHashEntry.keySet()) {
        ListenableFuture<?> materializationFuture = Objects
                .requireNonNull(fileMaterializationFuturesByFileHashEntry.get(fileEntry));
        if (!materializationFuture.isDone()) {
            LOG.warn(String.format("Materialization missing for: [%s] [sha1: %s]",
                    fileEntry.getPath().getPath(), fileEntry.getSha1()));
        }//from  w w w  .ja va2s .  c o m
    }
}

From source file:org.grouplens.lenskit.eval.script.ConfigMethodInvoker.java

Object finishBuilder(final Builder<?> builder) {
    List<ListenableFuture<?>> deps = getDeps(builder);
    clearDeps(builder);//from   ww w.  j av a2  s.  c om
    if (deps.isEmpty()) {
        return builder.build();
    } else {
        ListenableFuture<List<Object>> ideps = Futures.allAsList(deps);
        if (ideps.isDone()) {
            return builder.build();
        } else {
            return Futures.transform(ideps, new Function<List<Object>, Object>() {
                @Nullable
                @Override
                public Object apply(@Nullable List<Object> input) {
                    return builder.build();
                }
            });
        }
    }
}

From source file:bio.gcat.batch.Batch.java

public ListenableFuture<Result> execute(Collection<Tuple> tuples) {
    final Result result = new Result(tuples);
    Queue<Action> queue = new LinkedList<>(actions);
    if (queue.isEmpty())
        return new DefiniteListenableFuture<>(result);

    Action action;/*from  w ww .j  a  v  a  2s.  com*/
    Future<Collection<Tuple>> future = new DefiniteFuture<>(tuples);
    ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
    while ((action = queue.poll()) != null)
        future = service.submit(InjectionLogger.injectLogger(result, action.new Task(future)));

    final ListenableFuture<Collection<Tuple>> lastFuture = (ListenableFuture<Collection<Tuple>>) future;
    return new ListenableFuture<Result>() {
        @Override
        public boolean isDone() {
            return lastFuture.isDone();
        }

        @Override
        public boolean isCancelled() {
            return lastFuture.isCancelled();
        }

        @Override
        public Result get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            result.setTuples(lastFuture.get(timeout, unit));
            return result;
        }

        @Override
        public Result get() throws InterruptedException, ExecutionException {
            result.setTuples(lastFuture.get());
            return result;
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return lastFuture.cancel(mayInterruptIfRunning);
        }

        @Override
        public void addListener(Runnable listener, Executor executor) {
            lastFuture.addListener(listener, executor);
        }
    };
}

From source file:io.prestosql.plugin.hive.BackgroundHiveSplitLoader.java

private ListenableFuture<?> loadSplits() throws IOException {
    Iterator<InternalHiveSplit> splits = fileIterators.poll();
    if (splits == null) {
        HivePartitionMetadata partition = partitions.poll();
        if (partition == null) {
            return COMPLETED_FUTURE;
        }//from  w w w.  j  a  v  a 2 s .com
        return loadPartition(partition);
    }

    while (splits.hasNext() && !stopped) {
        ListenableFuture<?> future = hiveSplitSource.addToQueue(splits.next());
        if (!future.isDone()) {
            fileIterators.addFirst(splits);
            return future;
        }
    }

    // No need to put the iterator back, since it's either empty or we've stopped
    return COMPLETED_FUTURE;
}