如何在Java中使用超时调用某些阻塞方法?

时间:2009-07-22 10:18:03

标签: java concurrency

在Java中使用超时调用阻塞方法是否有一种标准的好方法?我希望能够做到:

// call something.blockingMethod();
// if it hasn't come back within 2 seconds, forget it

如果这是有道理的。

感谢。

11 个答案:

答案 0 :(得分:130)

你可以使用Executor:

ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
   public Object call() {
      return something.blockingMethod();
   }
};
Future<Object> future = executor.submit(task);
try {
   Object result = future.get(5, TimeUnit.SECONDS); 
} catch (TimeoutException ex) {
   // handle the timeout
} catch (InterruptedException e) {
   // handle the interrupts
} catch (ExecutionException e) {
   // handle other exceptions
} finally {
   future.cancel(true); // may or may not desire this
}

如果future.get在5秒内没有返回,则会抛出TimeoutException。可以在TimeUnit中以秒,分钟,毫秒或任何可用单位配置超时。

有关详细信息,请参阅JavaDoc

答案 1 :(得分:9)

您可以将呼叫包裹在FutureTask中,并使用get()的超时版本。

请参阅http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html

答案 2 :(得分:3)

There is also an AspectJ solution for that with jcabi-aspects library.

@Timeable(limit = 30, unit = TimeUnit.MINUTES)
public Soup cookSoup() {
  // Cook soup, but for no more than 30 minutes (throw and exception if it takes any longer
}

It can't get more succinct, but you have to depend on AspectJ and introduce it in your build lifecycle, of course.

There is an article explaining it further: Limit Java Method Execution Time

答案 3 :(得分:2)

另见Guava的TimeLimiter在幕后使用Executor。

答案 4 :(得分:1)

Thread thread = new Thread(new Runnable() {
    public void run() {
        something.blockingMethod();
    }
});
thread.start();
thread.join(2000);
if (thread.isAlive()) {
    thread.stop();
}

注意,不推荐使用stop,更好的选择是设置一些volatile布尔标志,在blockingMethod()里面检查并退出,如下所示:

import org.junit.*;
import java.util.*;
import junit.framework.TestCase;

public class ThreadTest extends TestCase {
    static class Something implements Runnable {
        private volatile boolean stopRequested;
        private final int steps;
        private final long waitPerStep;

        public Something(int steps, long waitPerStep) {
            this.steps = steps;
            this.waitPerStep = waitPerStep;
        }

        @Override
        public void run() {
            blockingMethod();
        }

        public void blockingMethod() {
            try {
                for (int i = 0; i < steps && !stopRequested; i++) {
                    doALittleBit();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        public void doALittleBit() throws InterruptedException {
            Thread.sleep(waitPerStep);
        }

        public void setStopRequested(boolean stopRequested) {
            this.stopRequested = stopRequested;
        }
    }

    @Test
    public void test() throws InterruptedException {
        final Something somethingRunnable = new Something(5, 1000);
        Thread thread = new Thread(somethingRunnable);
        thread.start();
        thread.join(2000);
        if (thread.isAlive()) {
            somethingRunnable.setStopRequested(true);
            thread.join(2000);
            assertFalse(thread.isAlive());
        } else {
            fail("Exptected to be alive (5 * 1000 > 2000)");
        }
    }
}

答案 5 :(得分:1)

试试这个。更简单的解决方案保证if block在时间限制内没有执行。该过程将终止并抛出异常。

try {
        TimeoutBlock timeoutBlock = new TimeoutBlock(10 * 60 * 1000);//set timeout in milliseconds
        Runnable block=new Runnable() {

            @Override
            public void run() {
                //TO DO write block of code 
            }
        };

        timeoutBlock.addBlock(block);// execute the runnable block 

    } catch (Throwable e) {
        //catch the exception here . Which is block didn't execute within the time limit
    }

示例:

{{1}}

答案 6 :(得分:1)

人们尝试以多种方式实现这一点真的很棒。但事实是,没有办法。

大多数开发人员都将尝试将阻塞调用放在另一个线程中,并设置一个将来的计时器。但是Java中没有办法从外部停止线程,更不用说一些非常具体的情况了,例如Thread.sleep()和Lock.lockInterruptably()方法,这些方法显式地处理线程中断。

所以实际上您只有3个通用选项:

  1. 将阻塞调用放在新线程上,如果时间到了,您就继续前进,让该线程挂起。在这种情况下,您应确保将线程设置为Daemon线程。这样,线程将不会阻止您的应用程序终止。

  2. 使用非阻塞Java API。因此,例如对于网络,请使用NIO2并使用非阻塞方法。要从控制台读取,请在阻止等之前使用Scanner.hasNext()。

  3. 如果阻塞调用不是IO,而是逻辑,则可以重复检查Thread.isInterrupted()以检查它是否在外部中断,并在该线程上进行另一个线程调用thread.interrupt()。阻塞线程

这门关于并发https://www.udemy.com/java-multithreading-concurrency-performance-optimization/?couponCode=CONCURRENCY的课程

如果您真的想了解它在Java中的工作方式,

会真正地了解这些基础知识。它实际上讨论了这些特定的限制和场景,以及如何在其中一场讲座中探讨这些限制和场景。

我个人尝试在不使用阻塞调用的情况下进行编程。例如,有一些工具包,例如Vert.x,可以非常轻松,高效地以非阻塞方式异步执行IO,而无需进行IO操作。

我希望对您有帮助

答案 7 :(得分:0)

假设blockingMethod只是睡了一些毫秒:

public void blockingMethod(Object input) {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

我的解决方案是使用wait()synchronized,如下所示:

public void blockingMethod(final Object input, long millis) {
    final Object lock = new Object();
    new Thread(new Runnable() {

        @Override
        public void run() {
            blockingMethod(input);
            synchronized (lock) {
                lock.notify();
            }
        }
    }).start();
    synchronized (lock) {
        try {
            // Wait for specific millis and release the lock.
            // If blockingMethod is done during waiting time, it will wake
            // me up and give me the lock, and I will finish directly.
            // Otherwise, when the waiting time is over and the
            // blockingMethod is still
            // running, I will reacquire the lock and finish.
            lock.wait(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

所以你可以替换

something.blockingMethod(input)

something.blockingMethod(input, 2000)

希望它有所帮助。

答案 8 :(得分:0)

您需要一个circuit breaker实现,就像GitHub上failsafe项目中的实现一样。

答案 9 :(得分:0)

我在这里给您完整的代码。您可以使用您的方法来代替我要调用的方法:

public class NewTimeout {
    public String simpleMethod() {
        return "simple method";
    }

    public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        Callable<Object> task = new Callable<Object>() {
            public Object call() throws InterruptedException {
                Thread.sleep(1100);
                return new NewTimeout().simpleMethod();
            }
        };
        Future<Object> future = executor.submit(task);
        try {
            Object result = future.get(1, TimeUnit.SECONDS); 
            System.out.println(result);
        } catch (TimeoutException ex) {
            System.out.println("Timeout............Timeout...........");
        } catch (InterruptedException e) {
            // handle the interrupts
        } catch (ExecutionException e) {
            // handle other exceptions
        } finally {
            executor.shutdown(); // may or may not desire this
        }
    }
}

答案 10 :(得分:0)

在阻塞队列的特殊情况下:

通用 java.util.concurrent.SynchronousQueue 有一个带有超时参数的 poll 方法。