Example usage for java.util.concurrent FutureTask get

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

Introduction

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

Prototype

public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 

Source Link

Usage

From source file:Main.java

private static <T> T callWithTimeout(final Callable<T> c, long timeout, ExecutorService timeoutExecutor)
        throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<T> task = new FutureTask<T>(c);
    timeoutExecutor.execute(task);//from  w  w w .  j  a v  a  2  s.c o m
    return task.get(timeout, TimeUnit.MILLISECONDS);
}

From source file:pl.nask.hsn2.service.scdbg.TimedScdbgProcess.java

private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit)
        throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<T> task = new FutureTask<T>(c);
    THREAD_POOL.execute(task);//from  ww w  .  j ava  2 s. co m
    return task.get(timeout, timeUnit);
}

From source file:Main.java

public static void blockUntilConnected(final SocketChannel channel, long timeout) throws IOException {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, timeout, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
        public Boolean call() {
            while (!channel.isConnected()) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                }//from   ww w.  j  a va 2 s. c  o m
            }
            return true;
        }
    });
    executor.execute(future);

    try {
        future.get(timeout, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        channel.close();
        throw new IOException(e);
    }
}

From source file:cc.gospy.core.util.StringHelper.java

public static String getMyExternalIp() {
    if (myExternalIp == null) {
        try {/*  w w w .j a  v  a  2  s  . c o m*/
            logger.info("Querying external ip...");
            FutureTask futureTask = new FutureTask<>(() -> {
                URL ipEcho = new URL("http://ipecho.net/plain");
                BufferedReader in = new BufferedReader(new InputStreamReader(ipEcho.openStream()));
                String resultIp = in.readLine();
                in.close();
                return resultIp;
            });
            futureTask.run();
            myExternalIp = (String) futureTask.get(3, TimeUnit.SECONDS);
            logger.info("My external ip: {}", myExternalIp);
        } catch (TimeoutException e) {
            myExternalIp = "unknown ip";
            logger.error("Get external ip failure, cause: Timeout (3 seconds)");
        } catch (Exception e) {
            myExternalIp = "unknown ip";
            logger.error("Get external ip failure, cause: {}", e.getMessage());
        }
    }
    return myExternalIp;
}

From source file:org.commonjava.indy.ftest.core.fixture.ThreadDumper.java

public static TestRule timeoutRule(int timeout, TimeUnit units) {
    return (base, description) -> new Statement() {
        public void evaluate() throws Throwable {
            System.out.printf("Setting up timeout: %d %s to wrap: %s\n", timeout, units, base);
            AtomicReference<Throwable> error = new AtomicReference<>();
            CountDownLatch latch = new CountDownLatch(1);
            FutureTask<Void> task = new FutureTask<>(() -> {
                try {
                    latch.countDown();//from w ww  .  j av a  2  s . c  om
                    base.evaluate();
                } catch (Throwable t) {
                    error.set(t);
                }

                return null;
            });

            ThreadGroup tg = new ThreadGroup("Test Timeout Group");
            Thread t = new Thread(tg, task, "Test Timeout Thread");
            t.setDaemon(true);
            t.start();

            try {
                System.out.println("Waiting for test to start.");
                latch.await();
            } catch (InterruptedException e) {
                error.set(e);
            }

            if (error.get() == null) {
                try {
                    System.out.println("Waiting for test to complete (or timeout)");
                    task.get(timeout, units);
                } catch (InterruptedException e) {
                    error.set(e);
                } catch (ExecutionException e) {
                    error.set(e.getCause());
                } catch (TimeoutException e) {
                    System.out.printf("Test timeout %d %s expired!\n", timeout, units.name());
                    dumpThreads();
                    StackTraceElement[] stackTrace = t.getStackTrace();
                    Exception currThreadException = new TestTimedOutException(timeout, units);
                    if (stackTrace != null) {
                        currThreadException.setStackTrace(stackTrace);
                        t.interrupt();
                    }

                    throw currThreadException;
                }
            }

            Throwable throwable = error.get();
            if (throwable != null) {
                throw throwable;
            }
        }
    };
}

From source file:com.skymobi.monitor.service.TaskService.java

public void scheduledTask(final Project project, final Task task) {
    final String projectName = project.getName();
    //first,cancel old task
    removeScheduled(projectName, task);//from w w w .  j  ava2  s.  com
    String taskKey = getTaskKey(projectName, task);
    ScheduledFuture<?> future = executor.schedule(new Runnable() {
        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            try {
                FutureTask _fuFutureTask = TaskService.this.runScript(task.getScript(), project);
                _fuFutureTask.get(task.getTimeout(), TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                logger.error("execute task timeout,use  {} (second), project={} , script={}",
                        new Object[] { (System.currentTimeMillis() - startTime) / 1000, projectName, task });
            } catch (Exception e) {
                logger.error("execute task ERROR,use  {} (second), project={} , script={}",
                        new Object[] { (System.currentTimeMillis() - startTime) / 1000, projectName, task });
                logger.error("execute task fail", e);
            }
            logger.info("execute task success,use {} (second) , project={} , taskName={}", new Object[] {
                    (System.currentTimeMillis() - startTime) / 1000, projectName, task.getName() });
        }
    }, new CronTrigger(task.getCron()));
    logger.info("add a new task {}", taskKey);
    futures.put(taskKey, future);
}

From source file:com.appleframework.monitor.service.TaskService.java

public void scheduledTask(final Project project, final Task task) {
    final String projectName = project.getName();
    //first,cancel old task
    removeScheduled(projectName, task);//from ww  w  .j  a v  a2 s  . c  o m
    String taskKey = getTaskKey(projectName, task);
    ScheduledFuture<?> future = executor.schedule(new Runnable() {
        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            try {
                FutureTask<CommandResult> _fuFutureTask = TaskService.this.runScript(task.getScript(), project);
                _fuFutureTask.get(task.getTimeout(), TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                logger.error("execute task timeout,use  {} (second), project={} , script={}",
                        new Object[] { (System.currentTimeMillis() - startTime) / 1000, projectName, task });
            } catch (Exception e) {
                logger.error("execute task ERROR,use  {} (second), project={} , script={}",
                        new Object[] { (System.currentTimeMillis() - startTime) / 1000, projectName, task });
                logger.error("execute task fail", e);
            }
            logger.info("execute task success,use {} (second) , project={} , taskName={}", new Object[] {
                    (System.currentTimeMillis() - startTime) / 1000, projectName, task.getName() });
        }
    }, new CronTrigger(task.getCron()));
    logger.info("add a new task {}", taskKey);
    futures.put(taskKey, future);
}

From source file:org.eclipse.virgo.ide.runtime.internal.core.command.AbstractJmxServerCommand.java

protected final Object execute(final JmxServerCommandTemplate template) throws TimeoutException {

    Callable<Object> deployOperation = new Callable<Object>() {

        public Object call() throws Exception {
            JMXConnector connector = null;
            try {
                connector = getJmxConnector();
                return template.invokeOperation(connector.getMBeanServerConnection());
            } finally {
                if (connector != null) {
                    try {
                        connector.close();
                    } catch (IOException e) {
                        SpringCore.log(e);
                    }/* w  ww  .  ja  v  a 2  s . c o  m*/
                }
            }
        }
    };

    FutureTask<Object> task = new FutureTask<Object>(deployOperation);
    ServerCorePlugin.EXECUTOR.submit(task);

    try {
        return task.get(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // swallow exception here
    } catch (ExecutionException e) {
        // swallow exception here
    }

    return null;
}

From source file:com.appleframework.monitor.action.MongoAction.java

@RequestMapping(value = "/projects/{projectName}/mongo/console", method = RequestMethod.POST)
public @ResponseBody BasicDBObject test(ModelMap map, @PathVariable String projectName, String script,
        Integer timeout) throws IOException, ExecutionException, TimeoutException, InterruptedException {

    Project project = projectService.findProject(projectName);
    FutureTask<CommandResult> futureTask = taskService.runScript(script, project);

    BasicDBObject result = null;//from   www . j a va 2 s  .c  o  m
    timeout = timeout != null ? timeout : 60;
    try {
        result = futureTask.get(timeout, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("execute task fail " + script, e);
        result = new BasicDBObject("err", e.toString());
    }
    logger.debug("run mongo script =[{}] ,result=[{}]", script, result);

    return result;
}

From source file:pt.webdetails.cpf.messaging.EventPublisher.java

private Runnable getPublishAndLogTask(final PluginEvent event) {
    Runnable publishAndLog = new Runnable() {
        @Override// w  w  w . j  ava 2  s  .c  o m
        public void run() {

            FutureTask<Result> toRun = getPublishTask(event);

            try {
                executor.execute(toRun);
                Result result = toRun.get(TIMEOUT, TimeUnit.SECONDS);
                String msg = "[" + event.getPlugin() + "] pushed event " + result;
                switch (result.getStatus()) {
                case OK:
                    logger.info(msg);
                    break;
                case ERROR:
                    logger.error(msg);
                    break;
                }
            } catch (Exception e) {
                toRun.cancel(true);
                logger.error("push failed: timeout reached: " + TIMEOUT + " seconds");
            }

        }
    };
    return publishAndLog;
}