java - Functionality for automatic retry after exception -


i have made abstract class automatically retry network calls if exception thrown.

  • i take care not retry after interruptedexception & unknownhostexception.
  • i retry 5 times. after each failure perform exponential off, starting 300ms going upto 1500ms.
public abstract class autoretry {    private object datatoreturn = null;   public object getdatatoreturn() {     return this.datatoreturn;   }    public autoretry() {      short retry = -1;     while (retry++ < staticdata.network_retry) {        try {         thread.sleep(retry * staticdata.network_call_wait);         this.datatoreturn = dowork();         break;       } catch (interruptedexception | unknownhostexception e) {         e.printstacktrace();         this.datatoreturn = null;         return;       } catch (ioexception e) {         e.printstacktrace();       }     }   }    protected abstract object dowork() throws ioexception; } 

i use follows :

final object dataafterwork = new autoretry() {        @override   protected object dowork() throws ioexception {     return; //a network call returns   } }.getdatatoreturn(); 

so implementation good/correct ?


edit

moved https://codereview.stackexchange.com/questions/87686

this looks pretty good, split running task retry. use generics, don't throw object about.

use java 8 lambda , return of method:

public static <t> optional<t> dowithretry(final supplier<t> t) {     (int retry = 0; retry <= staticdata.network_retry; ++retry) {         try {             thread.sleep(retry * staticdata.network_call_wait);             return optional.of(t.get());         } catch (interruptedexception | unknownhostexception e) {             logger.log(level.severe, "call failed.", e);             return optional.empty();         } catch (ioexception e) {             logger.log(level.warning, "call failed. retry.", e);         }     }     logger.log(level.severe, "call failed. retries exceeded.");     return optional.empty(); } 

also, use real logger, not printstacktrace...

usage:

final string data = dowithretry(() -> {    //do stuff  }); 

if lambda needs throw exception, you'll need define own @functionalinterface:

@functionalinterface interface stuffdoer<t> {     t dostuff() throws exception; } 

and use in method signature, you'll need handle generic exception.

pre-java 8 usage:

final string data = dowithretry(new stuffdoer<t>() {     @override     public t get() throws exception {         return null;     } }); 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -