How to make a "timeoutable" function in Java?

private String indexPage(URL currentPage) throws IOException {
    String content = "";
    is = currentPage.openStream();
    content = new Scanner( is ).useDelimiter( "\\Z" ).next();
    return content;
}

This is my function with which I am currently browsing the web. Function that problem:

content = new Scanner( is ).useDelimiter( "\\Z" ).next();

If the webpage is not responding or takes a lot of time, my thread just hangs over the specified line. What is the easiest way to interrupt this function if it takes more than 5 seconds to load a full load of this stream?

Thanks in advance!

+3
source share
5 answers

Instead of fighting with a separate observer stream, it may be enough for you (although this is not quite an answer to your requirement) if you enable connection and read timeouts in a network connection, for example:

URL url = new URL("...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
InputStream is = conn.getInputStream();

, 5 (5000 ), 10 (10000 ) , . , .

+7

.

+3

Google guava-libraries , :

TimeLimiter:

-, -. , target.someMethod(), DEFAULT_VALUE, 50 , ...

+3

Take a look at FutureTask ...

+1
source

Try interrupting the stream; many blocking calls in Java will continue when they receive an interrupt.

In this case, it contentshould be empty, but it Thread.isInterrupted()should be true.

0
source

Source: https://habr.com/ru/post/1719737/


All Articles