Ioanna Katsanou:
Me Java un método Java, lo que hace una conexión a un servicio web. A veces, este método toma demasiado tiempo para hacer la conexión. Quiero, por ejemplo, se tarda más de 5 segundos, después de detener el procedimiento actual y reiniciar todo por 3 veces más. Si todo momento fallan, entonces abortar por completo.
He escrito lo siguiente hasta ahora:
private ConnectionInterface connectWithTimeout() throws MalformedURLException, Exception {
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() throws InterruptedException, MalformedURLException, Exception {
return connectWithNoTimeout(); //This is the method that takes to long. If this method takes more than 5 seconds, I want to cancel and retry for 3 more times. Then abort completely.
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
System.out.println( "Timeout Occured");
} catch (InterruptedException e) {
System.out.println( " "InterruptedException Occured");
} catch (ExecutionException e) {
System.out.println( ""ExecutionException Occured");
} finally {
future.cancel(true); // here the method gets canceled. How do I retry it?
}
System.out.println( "Connected !!");
return connectWithNoTimeout();
}
private ConnectionInterface connectWithNoTimeout() throws MalformedURLException, Exception {}
Amongalen:
Su método ya tiene un tiempo de espera de 5 segundos. Todo lo que hay que hacer ahora es añadir algún tipo un bucle con 3 repeticiones. Es necesario un contador de tiempos de espera y un descanso después de intento exitoso. No está seguro de lo que quiere hacer cuando ocurren otras excepciones, se rompe añadido allí también. Siguiente código debe hacer el trabajo:
private ConnectionInterface connectWithTimeout() throws MalformedURLException, Exception {
int repeatCount = 0;
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() throws InterruptedException, MalformedURLException, Exception {
return connectWithNoTimeout(); //This is the method that takes to long. If this method takes more than 5 seconds, I want to cancel and retry for 3 more times. Then abort completely.
}
};
while (repeatCount < 3){
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
break;
} catch (TimeoutException ex) {
repeatCount++;
System.out.println( "Timeout Occured");
} catch (InterruptedException e) {
System.out.println( " "InterruptedException Occured");
break;
} catch (ExecutionException e) {
System.out.println( "ExecutionException Occured");
break;
} finally {
future.cancel(true); // here the method gets canceled. How do I retry it?
}
}
System.out.println( "Connected !!");
return connectWithNoTimeout();
}