java - 如果程序在n秒后没有返回任何内容,如何调用java中的函数

标签 java

我有一个这样的函数:

public boolean doLogin() {
    try {
        somemethodForLogin();
        return true;
    }  catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

在这种情况下,如果 somemethodForLogin() 花费的时间超过预期(例如 8 秒),我想返回 false 或抛出异常。我怎样才能做到这一点?

我在 somemethodForLogin() 之前添加了类似的内容:

new java.util.Timer().schedule(
    new java.util.TimerTask() {
        @Override
        public void run() {
            System.out.println("Returning after 8 seconds wait");
        }
    }, 8000);

但即使调用成功,它也总是会出现这种情况。

最佳答案

您可以使用可完成的 future 来调用登录,然后在超时情况下检索结果:

try {
    CompletableFuture.runAsync(() -> somemethodForLogin())
                 .get(8, TimeUnit.SECONDS);
    return true;
}catch(TimeoutException timeoutException) {
    //Timeout handline here
    return false; //or call other function
}

上面的 lambda 是 Supplier而不是Runnable .

CompletableFuture 的 get方法记录如下:

Waits if necessary for at most the given time for this future to complete, and then returns its result, if available.
TimeoutException - if the wait timed out

编辑:
以上是使用CompletableFuture<Void>因为调用正在使用 Runnable 。如果somemethodForLogin()返回一个值,您可以使用相同的 API,但调用 supplyAsync :

Object loginResult = CompletableFuture.supplyAsync(() -> somemethodForLogin())
        .get(8, TimeUnit.SECONDS);
//Just change the return types accordingly.

关于java - 如果程序在n秒后没有返回任何内容,如何调用java中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50501705/

相关文章:

java - 在 Netty 中读取字符串并用字节回复

java - 通过 Rest 将字符串返回方法转换为 jSON

java - 用java计算bittorent info_hash

java - 如何在不使用 ModelDriven 的情况下从 JSP 填充 POJO

java - 依赖Java的短路求值(编码风格)

java - 在 ActiveMQ 中启动时为 "Camel is shutting down"

Java - 相对于 JFrame 的光标位置

java - 在将对象传递给方法时初始化它是一个好习惯还是应该先初始化然后传递它?

java - 使用 Struts 2 实现 Spring Security

java - Java 和 VBScript 中模数的区别