Future.get()和InterruptedException异步线程

时间:2022-04-08 20:58:49

Im using asynchronous threading in my application WITH httpClient. I make a call using the Future Api like so

我在我的应用程序中使用异步线程与httpClient。我使用Future Api这样打电话

mStrResults = (String) rssFuture.get();

this call attempts to retrieve an html string returned from my Callable httpClient call() method.

此调用尝试检索从Callable httpClient call()方法返回的html字符串。

What i want to do however is ensure that the get method does not wait too long while executing the call() method. Should i pass a timeout parameter when calling rssFuture.get() or is it ok to just surround with a InterruptedException catch block?

但是我想要做的是确保get方法在执行call()方法时不会等待太长时间。我应该在调用rssFuture.get()时传递超时参数,还是可以用InterruptedException catch块进行环绕?

Also is there a default time which the asynchronous thread will wait before throwing an InterruptedException and if so can i set a custom value?

还有一个默认时间,异步线程在抛出InterruptedException之前会等待,如果可以,我可以设置自定义值吗?

2 个解决方案

#1


3  

You should pass a timeout parameter when calling rssFuture.get() and catch the TimeoutException. An InterruptedException will only happen if the thread running the your call gets interrupted with the Thread.interrupt method or if you call the cancel(true) method in the Future obj.

您应该在调用rssFuture.get()时传递timeout参数并捕获TimeoutException。只有在运行调用的线程被Thread.interrupt方法中断或者在Future obj中调用cancel(true)方法时,才会发生InterruptedException。

#2


3  

You should use Future.get(long timeout, TimeUnit unit), and catch TimeoutException. There is no default timeout for get(), it will wait forever.

您应该使用Future.get(long timeout,TimeUnit单元),并捕获TimeoutException。 get()没有默认超时,它将永远等待。

InterruptedException will not be thrown unless the thread calling Future.get() is interrupted.

除非调用Future.get()的线程被中断,否则不会抛出InterruptedException。

#1


3  

You should pass a timeout parameter when calling rssFuture.get() and catch the TimeoutException. An InterruptedException will only happen if the thread running the your call gets interrupted with the Thread.interrupt method or if you call the cancel(true) method in the Future obj.

您应该在调用rssFuture.get()时传递timeout参数并捕获TimeoutException。只有在运行调用的线程被Thread.interrupt方法中断或者在Future obj中调用cancel(true)方法时,才会发生InterruptedException。

#2


3  

You should use Future.get(long timeout, TimeUnit unit), and catch TimeoutException. There is no default timeout for get(), it will wait forever.

您应该使用Future.get(long timeout,TimeUnit单元),并捕获TimeoutException。 get()没有默认超时,它将永远等待。

InterruptedException will not be thrown unless the thread calling Future.get() is interrupted.

除非调用Future.get()的线程被中断,否则不会抛出InterruptedException。