title: ThreadLocal and @Aspect annotation
body: <p>I  am using @Aspect to implement a retry logic(max_retries = 5) for database stale connection problems.In this Advice I have a ThreadLocal object which keep tracks of how many times logic has retried to get connection and  it gets incremented whenever it cannot get connection so to avoid unlimited retries for  stale connection issue, maximum number of retries is 5(constant).</p>
  
  <p>But the problem I have is , in this @Aspect java class ThreadLocal never gets incremented  and this is causing endlees loop in the code, which of course should not retry after maximun number of retries, but never reach that count and does not break out of while loop.</p>
  
  <p>Please let me know if anybody had this problem with @Aspect and ThreadLcal object.</p>
  
  <p>I will be happy to share the code.</p>
  
  <pre><code>private static ThreadLocal&lt;Integer&gt; retryCounter= new ThreadLocal&lt;Integer&gt;() {};
  private static final String STALE_CONNECTION_EXCEPTION  = "com.ibm.websphere.ce.cm.StaleConnectionException";
  
  @Around("service") 
  public Object retryConnection(ProceedingJoinPoint pjp) throws Throwable {
          if (staleConnectionException == null) {
          return pjp.proceed();
      }
      Throwable exception = null;
      retryCounter.set(new Integer(0));
      while ( retryCounter.get() &lt; MAX_TRIES) {
          try {
              return pjp.proceed();
          }
          catch (AppDataException he) {
              exception = retry(he.getCause());
          }
          catch (NestedRuntimeException e) {
              exception = retry(e);
          }
      }
      if (exception != null) {
          Logs.error("Stale connection exception occurred, no more   retries left", this.getClass(), null);
          logException(pjp, exception);
          throw new AppDataException(exception);
      }
      return null;
  }
  
  private Throwable retry(Throwable e) throws Throwable {
      if (e instanceof NestedRuntimeException &amp;&amp; ((NestedRuntimeException)e).contains(staleConnectionException)) {
          retryCounter.set(retryCounter.get()+1);
          LogUtils.log("Stale connection exception occurred, retrying " +  retryCounter.get() + " of " + MAX_TRIES, this.getClass());
          return e;
      }
      else {
          throw e;
      }
  }
  </code></pre>