简体   繁体   中英

Best way to implement timeouts in java when making a HTTP request

Is it better to use the setSoTimeout on java.net.Socket or to wrap the service making the Http calls with another class with an ExecutorService and manage method timeouts with Futures?

Better is currently defined as good practice / more reliable / accurate. Not necessarily considering impact on performance unless it is considerable.

Edit: Should have also mentioned the connect(SocketAddress endpoint, int timeout) method on java.net.Socket to be clearer.

Neither? Use HttpURLConnection.setReadTimeout() and setConnectTimeout() .

BenG -- I think this is an "it depends on what you want" scenario -- if you normalize on the concurrency libs, that's fine, but you need to manage closing the socket yourself.

If you want to use the timeout, it'll do it for you.

If you are using the concurrency libs everywhere in your code and they feel really natural, sure, manually manage the socket yourself.

Technologically (if you look at the code inside of Socket) there isn't any big advantage to one or the other. Just make sure when you are handling your socket state in your Future, you are catching the potential IOExceptions so processing your future's doesn't potentially blow up your executing thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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