简体   繁体   English

当第三方方法调用挂起时,Java函数超时

[英]Timeout a java function when a third party method call hangs

I have a java application which calls a third party method, which can block indefinitely without throwing an exception. 我有一个调用第三方方法的Java应用程序,该方法可以无限期阻塞而不会引发异常。

Is it possible to wrap my method call in a timeout block (or thread, or other construct) such that I get back control after I assume the call is never returning? 是否可以将我的方法调用包装在超时块(或线程或其他构造)中,以便在我假设调用永不返回之后获得控制权?

The ThreadPoolExecutor should do what you need. ThreadPoolExecutor应该执行您需要的操作。 Using the awaitTermination method: 使用awaitTermination方法:

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. 阻塞直到关闭请求后所有任务完成执行,或者发生超时,或者当前线程被中断(以先发生的为准)。

all this multi threading is surely an answer but think if ur application is not a multi-threaded one, you can just store the timestamp of the moment you send the request and check it against the current timestamp. 所有这些多线程肯定是一个答案,但请考虑一下,如果您的应用程序不是多线程的,则可以只存储发送请求时的时间戳,并对照当前时间戳进行检查。 of course you will need a thread to keep track of the time. 当然,您将需要一个线程来跟踪时间。 but all in all you can use that same thread for this purpose for as many functions calls you need. 但总而言之,您可以为此目的使用同一线程来完成所需的许多函数调用。 so dont go on implementing the runnable in ur classes. 所以不要继续在ur类中实现runnable。 just make one tracker thread. 只需创建一个跟踪器线程即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM