Example usage for java.util.concurrent Future Future

List of usage examples for java.util.concurrent Future Future

Introduction

In this page you can find the example usage for java.util.concurrent Future Future.

Prototype

Future

Source Link

Usage

From source file:org.apache.gobblin.elasticsearch.writer.FutureCallbackHolder.java

public FutureCallbackHolder(final @Nullable WriteCallback callback, ExceptionLogger exceptionLogger,
        final MalformedDocPolicy malformedDocPolicy) {
    this.future = new Future<WriteResponse>() {
        @Override/*w ww  . j av  a 2s. c o  m*/
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return done.get();
        }

        @Override
        public WriteResponse get() throws InterruptedException, ExecutionException {
            Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.take();
            return getWriteResponseorThrow(writeResponseThrowablePair);
        }

        @Override
        public WriteResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.poll(timeout, unit);
            if (writeResponseThrowablePair == null) {
                throw new TimeoutException("Timeout exceeded while waiting for future to be done");
            } else {
                return getWriteResponseorThrow(writeResponseThrowablePair);
            }
        }
    };

    this.actionListener = new ActionListener<BulkResponse>() {
        @Override
        public void onResponse(BulkResponse bulkItemResponses) {
            if (bulkItemResponses.hasFailures()) {
                boolean logicalErrors = false;
                boolean serverErrors = false;
                for (BulkItemResponse bulkItemResponse : bulkItemResponses) {
                    if (bulkItemResponse.isFailed()) {
                        // check if the failure is permanent (logical) or transient (server)
                        if (isLogicalError(bulkItemResponse)) {
                            // check error policy
                            switch (malformedDocPolicy) {
                            case IGNORE: {
                                log.debug("Document id {} was malformed with error {}",
                                        bulkItemResponse.getId(), bulkItemResponse.getFailureMessage());
                                break;
                            }
                            case WARN: {
                                log.warn("Document id {} was malformed with error {}", bulkItemResponse.getId(),
                                        bulkItemResponse.getFailureMessage());
                                break;
                            }
                            default: {
                                // Pass through
                            }
                            }
                            logicalErrors = true;
                        } else {
                            serverErrors = true;
                        }
                    }
                }
                if (serverErrors) {
                    onFailure(new RuntimeException(
                            "Partial failures in the batch: " + bulkItemResponses.buildFailureMessage()));
                } else if (logicalErrors) {
                    // all errors found were logical, throw RuntimeException if policy says to Fail
                    switch (malformedDocPolicy) {
                    case FAIL: {
                        onFailure(new RuntimeException(
                                "Partial non-recoverable failures in the batch. To ignore these, set "
                                        + ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_MALFORMED_DOC_POLICY
                                        + " to " + MalformedDocPolicy.IGNORE.name()));
                        break;
                    }
                    default: {
                        WriteResponse writeResponse = new GenericWriteResponse<BulkResponse>(bulkItemResponses);
                        writeResponseQueue.add(new Pair<WriteResponse, Throwable>(writeResponse, null));
                        if (callback != null) {
                            callback.onSuccess(writeResponse);
                        }
                    }
                    }
                }
            } else {
                WriteResponse writeResponse = new GenericWriteResponse<BulkResponse>(bulkItemResponses);
                writeResponseQueue.add(new Pair<WriteResponse, Throwable>(writeResponse, null));
                if (callback != null) {
                    callback.onSuccess(writeResponse);
                }
            }
        }

        private boolean isLogicalError(BulkItemResponse bulkItemResponse) {
            String failureMessage = bulkItemResponse.getFailureMessage();
            return failureMessage.contains("IllegalArgumentException")
                    || failureMessage.contains("illegal_argument_exception")
                    || failureMessage.contains("MapperParsingException")
                    || failureMessage.contains("mapper_parsing_exception");
        }

        @Override
        public void onFailure(Exception exception) {
            writeResponseQueue.add(new Pair<WriteResponse, Throwable>(null, exception));
            if (exceptionLogger != null) {
                exceptionLogger.log(exception);
            }
            if (callback != null) {
                callback.onFailure(exception);
            }
        }
    };
}

From source file:org.apache.gobblin.scheduler.JobScheduler.java

/**
 * Schedule a job immediately.//from ww  w.j  a  va2  s. com
 *
 * <p>
 *   This method calls the Quartz scheduler to scheduler the job.
 * </p>
 *
 * @param jobProps Job configuration properties
 * @param jobListener {@link JobListener} used for callback,
 *                    can be <em>null</em> if no callback is needed.
 * @throws JobException when there is anything wrong
 *                      with scheduling the job
 */
public Future<?> scheduleJobImmediately(Properties jobProps, JobListener jobListener, JobLauncher jobLauncher) {
    Callable<Void> callable = new Callable<Void>() {
        @Override
        public Void call() throws JobException {
            try {
                runJob(jobProps, jobListener, jobLauncher);
            } catch (JobException je) {
                LOG.error("Failed to run job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), je);
                throw je;
            }
            return null;
        }
    };

    final Future<?> future = this.jobExecutor.submit(callable);
    return new Future() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (!cancelRequested) {
                return false;
            }
            boolean result = true;
            try {
                jobLauncher.cancelJob(jobListener);
            } catch (JobException e) {
                LOG.error("Failed to cancel job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), e);
                result = false;
            }
            if (mayInterruptIfRunning) {
                result &= future.cancel(true);
            }
            return result;
        }

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

        @Override
        public boolean isDone() {
            return future.isDone();
        }

        @Override
        public Object get() throws InterruptedException, ExecutionException {
            return future.get();
        }

        @Override
        public Object get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return future.get(timeout, unit);
        }
    };
}

From source file:org.apache.hadoop.hive.ql.exec.mr.ObjectCache.java

@Override
public <T> Future<T> retrieveAsync(String key, Callable<T> fn) throws HiveException {
    final T value = retrieve(key, fn);

    return new Future<T>() {

        @Override//from   ww w. j a v  a  2s.  c o  m
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public T get() throws InterruptedException, ExecutionException {
            return value;
        }

        @Override
        public T get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return value;
        }
    };
}

From source file:org.mule.transport.amqp.harness.AmqpTestClient.java

public Future<MuleMessage> setupFunctionTestComponentForFlow(FunctionalTestComponent functionalTestComponent)
        throws Exception {
    final CountDownLatch messageReceivedLatch = new CountDownLatch(1);
    final AtomicReference<MuleMessage> receivedMessageRef = new AtomicReference<MuleMessage>(null);

    functionalTestComponent.setEventCallback(new EventCallback() {
        public void eventReceived(MuleEventContext context, Object component) throws Exception {
            receivedMessageRef.set(context.getMessage());
            messageReceivedLatch.countDown();
        }/*  w  w  w.j  a  v a 2 s .c o  m*/
    });

    Future<MuleMessage> futureReceivedMessage = new Future<MuleMessage>() {
        public boolean cancel(boolean mayInterruptIfRunning) {
            throw new UnsupportedOperationException();
        }

        public boolean isCancelled() {
            throw new UnsupportedOperationException();
        }

        public boolean isDone() {
            throw new UnsupportedOperationException();
        }

        public MuleMessage get() throws InterruptedException, ExecutionException {
            throw new UnsupportedOperationException();
        }

        public MuleMessage get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            if (messageReceivedLatch.await(timeout, unit)) {
                return receivedMessageRef.get();
            } else {
                return null;
            }
        }
    };

    return futureReceivedMessage;
}