Cómo establecer el tiempo de espera en un método en Java y el método de reintento de una cantidad periódica del tiempo

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();
    }

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=239082&siteId=1
Recomendado
Clasificación