Est-ce que n'importe qui peut me guider sur la façon dont je peux utiliser un timeout simple en Java? En gros, dans mon projet, j'exécute une instruction br.readLine()
, qui lit une réponse d'un modem. Mais parfois, le modem ne répond pas. Pour cela, je souhaite ajouter un délai d’attente . Je recherche un code tel que:
try {
String s= br.readLine();
} catch(TimeoutException e) {
System.out.println("Time out has occurred");
}
Ce que vous cherchez peut être trouvé ici . Il existe peut-être un moyen plus élégant d’y parvenir, mais une approche possible est
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();
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();
Ce ne sont que des brouillons pour que vous puissiez avoir l’idée principale.
L'exemple 1 ne compilera pas. Cette version est compilée et exécutée. Il utilise des fonctionnalités lambda pour l'abréger.
/*
* [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";
}
}