首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ThreadLocal和@Aspect注解

ThreadLocal和@Aspect注解
EN

Stack Overflow用户
提问于 2013-05-29 23:08:45
回答 2查看 1.6K关注 0票数 0

我正在使用@Aspect为数据库过时的连接实现一个重试逻辑(max_retries= 5)这个建议我有一个ThreadLocal对象,它跟踪逻辑重试了多少次来获得连接,当它不能获得连接时它就会递增,所以为了避免对陈旧连接问题的无限重试,最大重试次数是5(常量)。

但我遇到的问题是,在这个@Aspect java类中,ThreadLocal永远不会递增,这会导致代码中的endlees循环,当然,在最大重试次数之后,endlees循环不应该重试,但永远不会达到那个计数,也不会中断while循环。

如果有人在@Aspect和ThreadLcal对象上遇到这个问题,请告诉我。

我很乐意分享代码。

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

发布于 2013-05-30 04:24:07

正如评论中提到的,不确定为什么要使用线程本地...但是考虑到你是,可能导致无限循环的原因是递归地使用这个方面。通过调试器运行它或分析它,以查看您是否以嵌套的方式命中相同的方面。

票数 1
EN

Stack Overflow用户

发布于 2013-05-30 04:02:19

老实说,看看您的代码,我认为您最好根本不这样做,而只是在您的连接池中配置连接测试(假设您正在使用一个连接池):http://pic.dhe.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.nd.multiplatform.doc/info/ae/ae/tdat_pretestconn.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16817582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档