Java: how to ensure that interface methods don’t take more time than x?

I have an interface method Boolean right (). If it does not answer within one second, it should return false

Solution

Yes, this can be used, for example, Java util. concurrent. Future < V > (standard interface for asynchronous calculation results of type V), combined with the method get (long timeout, timeunit) Among other exceptions, this method may throw timeoutexception, but return the calculation result during normal execution

In this case, you need a future < Boolean >, use get (1, timeunit. Seconds) in the try catch block, and handle timeoutexception according to your specification

The specific implementations available are futuretask < V > and swingworker < T, V > If this is in the context of a swing application, you will use the latter

You can also have a look

>Effective Java 2nd Edition, item 68: prefer executing programs and tasks to threads > concurrent programming with J2SE 5.0 > java tutorials / concurrency > java tutorials / swing / how to use threads – if you use swing, please read the important content!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>