问题
Can anyone guide me on how I can use a simple timeout in java? Basically in my project I'm executing a statement br.readLine()
, which is reading a response from a modem. But sometimes the modem isn't responding. For that purpose I want to add a timeout.
I'm looking for a code like:
try {
String s= br.readLine();
} catch(TimeoutException e) {
System.out.println("Time out has occurred");
}
回答1:
What you are looking for can be found here. It may exist a more elegant way to accomplish that, but one possible approach is
Option 1 (preferred):
final Duration timeout = Duration.ofSeconds(30);
ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<String> handler = executor.submit(new Callable() {
@Override
public String call() throws Exception {
return requestDataFromModem();
}
});
try {
handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
handler.cancel(true);
}
executor.shutdownNow();
Option 2:
final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final Future<String> handler = executor.submit(new Callable() {
@Override
public String call() throws Exception {
return requestDataFromModem();
}
});
executor.schedule(new Runnable() {
@Override
public void run(){
handler.cancel(true);
}
}, timeout.toMillis(), TimeUnit.MILLISECONDS);
executor.shutdownNow();
Those are only a draft so that you can get the main idea.
回答2:
The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.
/*
* [RollYourOwnTimeouts.java]
*
* Summary: How to roll your own timeouts.
*
* Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
*
* Licence: This software may be copied and used freely for any purpose but military.
* http://mindprod.com/contact/nonmil.html
*
* Requires: JDK 1.8+
*
* Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
*
* Version History:
* 1.0 2016-06-28 initial version
*/
package com.mindprod.example;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static java.lang.System.*;
/**
* How to roll your own timeouts.
* Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2016-06-28 initial version
* @since 2016-06-28
*/
public class RollYourOwnTimeout
{
private static final long MILLIS_TO_WAIT = 10 * 1000L;
public static void main( final String[] args )
{
final ExecutorService executor = Executors.newSingleThreadExecutor();
// schedule the work
final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );
try
{
// where we wait for task to complete
final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
out.println( "result: " + result );
}
catch ( TimeoutException e )
{
err.println( "task timed out" );
future.cancel( true /* mayInterruptIfRunning */ );
}
catch ( InterruptedException e )
{
err.println( "task interrupted" );
}
catch ( ExecutionException e )
{
err.println( "task aborted" );
}
executor.shutdownNow();
}
/**
* dummy method to read some data from a website
*/
private static String requestDataFromWebsite()
{
try
{
// force timeout to expire
Thread.sleep( 14_000L );
}
catch ( InterruptedException e )
{
}
return "dummy";
}
}
回答3:
Use this line of code:
Thread.sleep(1000);
It will sleep for 1 second.
来源:https://stackoverflow.com/questions/19456313/simple-timeout-in-java