pk2
pk2

Reputation: 15

ThreadLocal and @Aspect annotation

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).

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.

Please let me know if anybody had this problem with @Aspect and ThreadLcal object.

I will be happy to share the code.

private static ThreadLocal<Integer> retryCounter= new ThreadLocal<Integer>() {};
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() < 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 && ((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;
    }
}

Upvotes: 0

Views: 2117

Answers (2)

Nitsan Wakart
Nitsan Wakart

Reputation: 2909

As mentioned in the comments, not sure why you are using a thread local... but given that you are, what might be causing the infinite loop is recursive use of this aspect. Run it through a debugger or profile it to see if you are hitting the same aspect in a nested fashion.

Upvotes: 1

Jukka
Jukka

Reputation: 4663

To be honest, looking at your code, I think you would be better off not doing this at all, but rather just configure connection testing in your connection pool (assuming you are using one): http://pic.dhe.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.nd.multiplatform.doc/info/ae/ae/tdat_pretestconn.html

Upvotes: 0

Related Questions