Example usage for java.util.concurrent FutureTask FutureTask

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

Introduction

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

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:com.betfair.cougar.client.socket.ExecutionVenueNioClient.java

/**
 * Stops the client./*from www  .j av  a2 s . c  o m*/
 */
public synchronized FutureTask<Boolean> stop() {
    this.sessionFactory.stop();
    if (rpcTimeoutChecker != null) {
        rpcTimeoutChecker.stop();
    }
    final FutureTask<Boolean> futureTask = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            while (ExecutionVenueNioClient.this.sessionFactory.isConnected()) {
                Thread.sleep(50);
            }
            return true;
        }
    });
    final Thread thread = new Thread(futureTask);
    thread.setDaemon(true);
    thread.start();
    return futureTask;
}

From source file:com.vmware.appfactory.build.service.BuildServiceImpl.java

/**
 * Submit all the capture requests via the executor.
 * For a single request, submit the request synchronously to the queue. Otherwise,
 * submit all in a FutureTask./* www. j  a  v a 2s.c  o  m*/
 *
 * @param captureRequests a capture request
 * @throws DsException
 * @throws AfNotFoundException
 * @throws WpException
 */
@Override
public void submitTasks(@Nonnull final CaptureRequestImpl[] captureRequests)
        throws DsException, WpException, AfNotFoundException {

    if (captureRequests.length == 1) {
        submitSingleTask(captureRequests[0]);
        return;
    }

    final FutureTask<Void> future = new FutureTask<Void>(new Callable<Void>() {
        @Override
        public Void call() {
            for (CaptureRequestImpl req : captureRequests) {
                submitSingleTask(req);
            }
            String msg = String.format("All %d capture requests are being queued.", captureRequests.length);
            _log.debug(msg);
            NotificationService.INSTANCE.newInfoEvent(msg, Component.builds);
            return null;
        }
    });

    _executor.execute(future);
}

From source file:com.alibaba.napoli.metamorphosis.client.extension.producer.LocalMessageStorageManager.java

/**
 * ????,?(???????)//from   w  ww .j  a v a2  s  .  c o m
 * 
 * @param topic
 * @param partition
 * @param recoverer
 *            ?????
 * @return ?????
 * */
@Override
public boolean recover(final String topic, final Partition partition, final MessageRecoverer recoverer) {

    final String name = this.generateKey(topic, partition);
    final FutureTask<Boolean> recoverTask = new FutureTask<Boolean>(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            final AtomicLong count = new AtomicLong(0);
            try {

                final Store store = LocalMessageStorageManager.this.getOrCreateStore(topic, partition);

                this.innerRecover(store, recoverer, count, name);
            } catch (final Throwable e) {
                log.error("SendRecover?????,name=" + name, e);
            } finally {
                log.info("SendRecover????,name=" + name + ",???"
                        + count.get() + "?");
                LocalMessageStorageManager.this.topicRecoverTaskMap.remove(name);
            }
            return true;
        }

        private void innerRecover(final Store store, final MessageRecoverer recoverer, final AtomicLong count,
                final String name) throws IOException, Exception {
            final Iterator<byte[]> it = store.iterator();
            while (it.hasNext()) {
                final byte[] key = it.next();
                final Message msg = (Message) LocalMessageStorageManager.this.deserializer
                        .decodeObject(store.get(key));
                recoverer.handle(msg);
                try {
                    store.remove(key);
                    count.incrementAndGet();
                    if (count.get() % 20000 == 0) {
                        log.info("SendRecover " + name + "????:" + count.get());
                    }
                } catch (final IOException e) {
                    log.error("SendRecover remove message failed", e);
                }
            }
        }
    });

    final FutureTask<Boolean> ret = this.topicRecoverTaskMap.putIfAbsent(name, recoverTask);
    if (ret == null) {
        this.threadPoolExecutor.submit(recoverTask);
        return true;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("SendRecover?????,????,name=" + name);
        }
        return false;
    }

}

From source file:io.teak.sdk.DeviceConfiguration.java

private void fetchAdvertisingInfo(@NonNull final Context context) {
    final DeviceConfiguration _this = this;
    final FutureTask<AdvertisingIdClient.Info> adInfoFuture = new FutureTask<>(
            new RetriableTask<>(100, 7000L, new Callable<AdvertisingIdClient.Info>() {
                @Override/*from ww w .java  2  s  .c o  m*/
                public AdvertisingIdClient.Info call() throws Exception {
                    int googlePlayStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
                    if (googlePlayStatus == ConnectionResult.SUCCESS) {
                        return AdvertisingIdClient.getAdvertisingIdInfo(context);
                    }
                    throw new Exception("Retrying GooglePlayServicesUtil.isGooglePlayServicesAvailable()");
                }
            }));
    new Thread(adInfoFuture).start();

    // TODO: This needs to be re-checked in case it's something like SERVICE_UPDATING or SERVICE_VERSION_UPDATE_REQUIRED
    int googlePlayStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
    if (googlePlayStatus == ConnectionResult.SUCCESS) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    AdvertisingIdClient.Info adInfo = adInfoFuture.get();

                    // Inform listeners Ad Info has changed
                    if (adInfo != _this.advertsingInfo) {
                        _this.advertsingInfo = adInfo;
                        synchronized (eventListenersMutex) {
                            for (EventListener e : eventListeners) {
                                e.onAdvertisingInfoChanged(_this);
                            }
                        }
                    }
                } catch (Exception e) {
                    if (Teak.isDebug) {
                        Log.e(LOG_TAG, "Couldn't get Google Play Advertising Information.");
                    }
                }
            }
        }).start();
    }
}

From source file:com.rowland.hashtrace.utility.AsyncTaskEx.java

/**
 * Creates a new asynchronous task. This constructor must be invoked on the
 * UI thread.//from w  w w  .  j  a  v  a  2 s. c o m
 */
public AsyncTaskEx() {
    mWorker = new WorkerRunnable<Params, Result>() {
        @Override
        public Result call() throws Exception {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            return doInBackground(mParams);
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        @SuppressWarnings("unchecked")
        @Override
        protected void done() {
            Message message;
            Result result = null;

            try {
                result = get();
            } catch (InterruptedException e) {
                android.util.Log.w(LOG_TAG, e);
            } catch (ExecutionException e) {
                throw new RuntimeException("An error occured while executing doInBackground()", e.getCause());
            } catch (CancellationException e) {
                message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
                        new AsyncTaskExResult<Result>(AsyncTaskEx.this, (Result[]) null));
                message.sendToTarget();
                return;
            } catch (Throwable t) {
                throw new RuntimeException("An error occured while executing " + "doInBackground()", t);
            }

            message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                    new AsyncTaskExResult<Result>(AsyncTaskEx.this, result));
            message.sendToTarget();
        }
    };
}

From source file:ubic.gemma.loader.expression.geo.GeoFamilyParser.java

@Override
public void parse(InputStream is) throws IOException {
    if (is == null) {
        throw new IOException("Inputstream was null");
    }/*from  w  w w . j a va  2  s  .com*/

    if (is.available() == 0) {
        throw new IOException("No bytes to read from the input stream.");
    }

    final BufferedReader dis = new BufferedReader(new InputStreamReader(is));

    log.debug("Parsing....");

    final ExecutorService executor = Executors.newSingleThreadExecutor();

    FutureTask<Exception> future = new FutureTask<Exception>(new Callable<Exception>() {
        @Override
        public Exception call() {
            try {
                return doParse(dis);
            } catch (Exception e) {
                log.error(e, e);
                return e;
            }

        }
    });

    executor.execute(future);
    executor.shutdown();

    while (!future.isDone() && !future.isCancelled()) {
        try {
            TimeUnit.SECONDS.sleep(5L);
        } catch (InterruptedException e) {
            // probably cancelled.
            return;
        }
        log.info(parsedLines + " lines parsed.");
    }

    try {
        Exception e = future.get();
        if (e != null) {
            log.error(e.getMessage());
            throw new RuntimeException(e.getCause());
        }
    } catch (ExecutionException e) {
        throw new RuntimeException("Parse failed", e.getCause());
    } catch (java.util.concurrent.CancellationException e) {
        throw new RuntimeException("Parse was cancelled", e.getCause());
    } catch (InterruptedException e) {
        throw new RuntimeException("Parse was interrupted", e.getCause());
    }

    executor.shutdownNow();

    assert future.isDone();
    // assert executor.isTerminated();

    log.info("Done parsing.");
}

From source file:com.test.test.MultipleRequestsForServerTest.java

@Test
public void testMultiClientsForServer() throws Exception {
    // Number of threads
    final int size = 30;

    LOG.debug("clientSimple1:" + clientSimple);

    List<IServiceSimple> serviceSimpleList = new ArrayList<IServiceSimple>();
    for (int i = 0; i < size; i++) {
        IServiceSimple proxyService = clientSimple.getProxy(IServiceSimple.class);
        LOG.debug("proxyService:" + proxyService);
        serviceSimpleList.add(proxyService);
    }/*  ww  w  .  j a  va  2s  .  c o  m*/

    List<ClientCallableForServer> clientCallableList = new ArrayList<ClientCallableForServer>();

    for (int i = 0; i < size; i++) {
        clientCallableList.add(new ClientCallableForServer(serviceSimpleList.get(i), i));
    }

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallableForServer clientCallable : clientCallableList) {
        futureTaskList.add(new FutureTask<String>(clientCallable));
    }

    long beginTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(futureTaskList.size());
    for (FutureTask<String> futureTask : futureTaskList) {
        executor.execute(futureTask);
    }

    boolean ready = false;
    int[] dones = new int[futureTaskList.size()];
    String[] writes = new String[futureTaskList.size()];

    int indexValue = 0;
    while (!ready) {

        int count = 0;
        indexValue = 0;
        for (FutureTask<String> futureTask : futureTaskList) {
            if (futureTask.isDone() & dones[indexValue] == 0) {
                writes[indexValue] = futureTask.get();
                dones[indexValue] = 1;
            }
            indexValue++;
        }

        for (int k = 0; k < dones.length; k++) {
            if (dones[k] == 1) {
                count++;
            }
        }

        if (count == futureTaskList.size()) {
            ready = true;
        }

        //            Thread.sleep(500);
    }

    LOG.debug("\n\n\n ====== DONE ====== ");
    LOG.debug("  time:" + (System.currentTimeMillis() - beginTime) + "ms\n\n");
    executor.shutdown();

    for (int i = 0; i < writes.length; i++) {
        LOG.debug("- " + writes[i]);
    }
    LOG.debug("\n\n\n ====== DONE ====== \n\n");

    Thread.sleep(20000);
    LOG.debug("\n\n\n\n+++++++++++++++++++++++++");
    LOG.debug("New system:");
    IServiceSimple proxyService2 = clientSimple.getProxy(IServiceSimple.class);
    proxyService2.functionNumber1("1", "1");
}

From source file:org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.java

public void invokeAsync(MessageContext request, EndpointCallback callback) {
    if (log.isDebugEnabled()) {
        log.debug("Invoking service endpoint: " + serviceImplClass.getName());
        log.debug("Invocation pattern: two way, async");
    }/*w w w. java 2 s .  co m*/

    initialize(request);

    OperationDescription operationDesc = Utils.getOperationDescription(request);

    Object[] methodInputParams = createRequestParameters(request);

    Method target = getJavaMethod(request, serviceImplClass);
    if (log.isDebugEnabled()) {
        // At this point, the OpDesc includes everything we know, including the actual method
        // on the service impl we will delegate to; it was set by getJavaMethod(...) above.
        log.debug("JavaBeanDispatcher about to invoke using OperationDesc: " + operationDesc.toString());
    }

    EndpointInvocationContext eic = (EndpointInvocationContext) request.getInvocationContext();
    ClassLoader cl = getContextClassLoader();

    AsyncInvocationWorker worker = new AsyncInvocationWorker(target, methodInputParams, cl, eic);
    FutureTask task = new FutureTask<AsyncInvocationWorker>(worker);

    ExecutorFactory ef = (ExecutorFactory) FactoryRegistry.getFactory(ExecutorFactory.class);
    Executor executor = ef.getExecutorInstance(ExecutorFactory.SERVER_EXECUTOR);
    // If the property has been set to disable thread switching, then we can 
    // do so by using a SingleThreadedExecutor instance to continue processing
    // work on the existing thread.
    Boolean disable = (Boolean) request.getProperty(ServerConstants.SERVER_DISABLE_THREAD_SWITCH);
    if (disable != null && disable.booleanValue()) {
        if (log.isDebugEnabled()) {
            log.debug("Server side thread switch disabled.  Setting Executor to the SingleThreadedExecutor.");
        }
        executor = new SingleThreadedExecutor();
    }
    executor.execute(task);

    return;
}

From source file:com.dm.estore.common.config.Cfg.java

private void startWatcher(final String configDirPath) throws IOException {
    Path path = Paths.get(configDirPath);
    path.register(watchService, ENTRY_MODIFY);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*ww  w  .  j  av a 2  s  .com*/
        public void run() {
            try {
                keepWatching = false;
                watchService.close();
            } catch (IOException e) {
                LOG.error("Unable to stop configuration watch service", e);
            }
        }
    });

    FutureTask<Integer> watchTask = new FutureTask<>(new Callable<Integer>() {
        private int totalEventCount;

        @Override
        public Integer call() throws Exception {
            while (keepWatching) {
                try {
                    WatchKey watchKey = watchService.poll(5, TimeUnit.SECONDS);
                    if (watchKey != null) {
                        boolean updateConfiguration = false;
                        for (WatchEvent<?> event : watchKey.pollEvents()) {
                            LOG.debug("Configuration changed: " + event.kind());
                            updateConfiguration = true;
                            totalEventCount++;
                        }
                        if (!watchKey.reset()) {
                            // handle situation no longer valid
                            keepWatching = false;
                        } else {
                            if (updateConfiguration) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep(1000);
                                            getConfig().getString(CommonConstants.Cfg.CFG_UPDATE_TRIGGER);
                                        } catch (InterruptedException ex) {
                                            // do nothing
                                        }
                                    }
                                }).start();
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            return totalEventCount;
        }
    });
    new Thread(watchTask).start();
}

From source file:org.apache.hive.spark.client.SparkSubmitSparkClient.java

@Override
protected Future<Void> launchDriver(String isTesting, RpcServer rpcServer, String clientId) throws IOException {
    Callable<Void> runnable;

    String cmd = Joiner.on(" ").join(argv);
    LOG.info("Running client driver with argv: {}", cmd);
    ProcessBuilder pb = new ProcessBuilder("sh", "-c", cmd);

    // Prevent hive configurations from being visible in Spark.
    pb.environment().remove("HIVE_HOME");
    pb.environment().remove("HIVE_CONF_DIR");
    // Add credential provider password to the child process's environment
    // In case of Spark the credential provider location is provided in the jobConf when the job is submitted
    String password = getSparkJobCredentialProviderPassword();
    if (password != null) {
        pb.environment().put(Constants.HADOOP_CREDENTIAL_PASSWORD_ENVVAR, password);
    }/*from   w w w. jav  a  2s  .c om*/
    if (isTesting != null) {
        pb.environment().put("SPARK_TESTING", isTesting);
    }

    final Process child = pb.start();
    String threadName = Thread.currentThread().getName();
    final List<String> childErrorLog = Collections.synchronizedList(new ArrayList<String>());
    final LogRedirector.LogSourceCallback callback = () -> isAlive;

    LogRedirector.redirect("spark-submit-stdout-redir-" + threadName,
            new LogRedirector(child.getInputStream(), LOG, callback));
    LogRedirector.redirect("spark-submit-stderr-redir-" + threadName,
            new LogRedirector(child.getErrorStream(), LOG, childErrorLog, callback));

    runnable = () -> {
        try {
            int exitCode = child.waitFor();
            if (exitCode != 0) {
                List<String> errorMessages = new ArrayList<>();
                synchronized (childErrorLog) {
                    for (String line : childErrorLog) {
                        if (StringUtils.containsIgnoreCase(line, "Error")) {
                            errorMessages.add("\"" + line + "\"");
                        }
                    }
                }

                String errStr = errorMessages.isEmpty() ? "?" : Joiner.on(',').join(errorMessages);

                rpcServer.cancelClient(clientId, new RuntimeException("spark-submit process failed "
                        + "with exit code " + exitCode + " and error " + errStr));
            }
        } catch (InterruptedException ie) {
            LOG.warn(
                    "Thread waiting on the child process (spark-submit) is interrupted, killing the child process.");
            rpcServer.cancelClient(clientId,
                    "Thread waiting on the child process (spark-submit) is interrupted");
            Thread.interrupted();
            child.destroy();
        } catch (Exception e) {
            String errMsg = "Exception while waiting for child process (spark-submit)";
            LOG.warn(errMsg, e);
            rpcServer.cancelClient(clientId, errMsg);
        }
        return null;
    };

    FutureTask<Void> futureTask = new FutureTask<>(runnable);

    Thread driverThread = new Thread(futureTask);
    driverThread.setDaemon(true);
    driverThread.setName("SparkSubmitMonitor");
    driverThread.start();

    return futureTask;
}