11/16/2018

Retry Design

Sometimes, Network is inherently unreliable. Connections will occasionally time out or be dropped. For some reasons, we still want to try to establish a connection to a remote endpoint which went down.

There is straightforward answer which wrote down below code to resolve it.

      try
      {
          this.conn = connect();
      }
      catch (Exception e)
      {
         for (int i = 0; i < maxAttempts; i++)
         {
            try { Thread.sleep(1000); } catch (InterruptedException e) {};
            this.conn = connect();
         }
      }

But the solution is difficult to maintain and a lack of flexibility. If we are using java8, this may change below to more be useful.

public static <T> Object retry(Supplier<T> function, int retryCount) throws Exception
   {
      while (0 < retryCount)
      {
         try
         {
            return function.get();
         }
         catch (Exception e)
         {
            if ((retryCount--) == 0)
               throw e;
         }
      }
      return null;
   }
   

Based on above two solutions, we still try to add extra code into connection logic and the unnecessary design. I think there's much better to use if you are using spring or AOP concept.

 @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 500))
 public void establishConnection() {
    this.connection = newConnection();
 } 

Code is simply and easy to use.

Reference

spring-retry

1 comment:

  1. Anonymous5/12/22 23:41

    Some of the most well-liked sport show-style titles available at JackpotCity Casino are Monopoly Live and Dream Catcher. Interac From your bank to your casino account, electronically. Perfect Strategy Blackjack Exciting new options to check out in 카지노사이트 blackjack. Dedicated groups as Customer Support Live and Technical Support are handling the top person inquiries and assists them and the account managers within the event of gaming or technical difficulties. Marketing instruments that enable operators to run and handle their very own promotions in a classy, configurable method. You will see an orange button within the high proper that says “Join.” Click on the button to register.

    ReplyDelete