A mechanism for implementing method retries in Java

Source: Internet
Author: User

There is a requirement that when a method is called to throw an exception, such as when a remote interface is invoked through HttpClient, a TimeOut exception is reported because of network reasons, or the requested interface returns information similar to "in process" and needs to be repeatedly checked for results. We hope that the current approach can be repeated in this particular case, and that we do not repeat it if our expectations are met. Furthermore, we want to be able to control the number of retries and do not want to execute indefinitely.

Java has a variety of timing tasks implementation, such as Spring Schedule,quartz, and so on, a little think about it, obviously does not meet our needs. Recursion is fine, but there are some problems, first look at the implementation of recursion:

    Private intRetrytimes = 3; @Test Public voidUppermethod () {Method ("123", "456"); }     Public voidmethod (String param1, String param2) {System.out.println (param1+param2); //some other operations, but do not get the expected return result, or throw an exception        BooleanIsexception =true; if(isexception && retrytimes > 0) {Retrytimes--;        Method (param1, param2); }    }

Method methods need to be repeated, executed 3 times, plus the first execution, altogether 4 times. If it is an exception, the method is called recursively within the catch. If the "in process" condition is returned, the decision is made whether a recursive call is required.

The problem here is to define a global variable such as Retrytimes, which is not elegant, and if you need to repeat the method more than the same number of repetitions, you need to define multiple global variables. Recursion can be optimized:

@Test Public voidUppermethod () {Method (3, "123", "456"); }     Public voidMethodintretrytimes,string param1, String param2) {System.out.println (param1+param2); //some other operations, but do not get the expected return result, or throw an exception        BooleanIsexception =true; if(isexception && retrytimes > 0) {Method (--retrytimes, param1, param2); }    }

The global variables are removed, but the method approach has a retrytimes variable that is independent of its own logic and not elegant. If there are many parameters, it will appear chaotic.

Here's an elegant way to do it:

    @Test    publicvoid  Mainmethod () {        Submethod ("123", "456");    }     publicvoid  Submethod (String param1, String param2) {        + param2);        Retryutil.setretrytimes (3). Retry (param1, param2);    }

Added a Retryutil tool class, set the retry count, and then pass in the parameters of the current method for repeated execution. The focus here is on the implementation of Retryutil:

 Public classRetryutil {Private StaticThreadlocal<integer> Retrytimesinthread =NewThreadlocal<>(); /*** Set the current method retry Count * *@paramRetrytimes *@return     */     Public Staticretryutil setretrytimes (Integer retrytimes) {if(Retrytimesinthread.get () = =NULL) Retrytimesinthread.set (retrytimes); return NewRetryutil (); }    /*** Retry Current method * <p> all parameters of incoming caller method in order </p> * *@paramargs *@return     */     PublicObject Retry (Object ... args) {Try{Integer Retrytimes=Retrytimesinthread.get (); if(retrytimes <= 0) {retrytimesinthread.remove (); return NULL; } retrytimesinthread.set (--retrytimes); String Upperclassname= Thread.CurrentThread (). Getstacktrace () [2].getclassname (); String Uppermethodname= Thread.CurrentThread (). Getstacktrace () [2].getmethodname (); Class Clazz=Class.forName (upperclassname); Object TargetObject=clazz.newinstance (); Method Targetmethod=NULL;  for(Method method:clazz.getDeclaredMethods ()) {if(Method.getname (). Equals (Uppermethodname)) {Targetmethod=method;  Break; }            }            if(Targetmethod = =NULL)                return NULL; Targetmethod.setaccessible (true); returnTargetmethod.invoke (TargetObject, args); } Catch(Exception e) {e.printstacktrace (); return NULL; }    }}

To prevent concurrency problems in multithreaded situations, a ThreadLocal variable is defined to store the number of retries for the current thread. The retry count is then set by Setretrytimes, a static method, and a Retryutil object is returned.

The caller invokes the retry method through the returned Retryutil object to implement the retry. The retry method receives a mutable parameter because the caller's actual argument is not deterministic, and this requires that all parameters of the caller's method be passed in order.

Next, determine if the ThreadLocal variable is less than or equal to 0, if it is, the number of repetitions has been reached, returns NULL, and if not, let the ThreadLocal variable subtract one. Next:

String upperclassname = Thread.CurrentThread (). Getstacktrace () [2= Thread.CurrentThread (). Getstacktrace () [ 2].getmethodname ();

To get the upper method name and upper class name for the current method (retry). Thread.CurrentThread (). Getstacktrace () Gets the thread's array of method stacks, the second element of the array thread.currentthread (). Getstacktrace () [1] is the current method stack, and the third element Thread.CurrentThread (). Getstacktrace () [2] is the upper method stack, the method name and the class name of the upper method are obtained through the stack frame of the upper method.

The following is a reflection of all the methods of the class, the loop to determine whether the method name is equal to the method to be repeated, if so, execute the method, the parameter is passed in the variable parameter.

It may be said that reflection can be time-consuming, but I don't think the number of retries will be too much for the above requirements, so performance is acceptable.

A mechanism for implementing method retries in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.