2013-06-26 27 views
1

我有AOP配置如下在aop中爲單線程和多線程程序編寫方面的最佳實踐是什麼?

aop:config> 
     <aop:aspect id="Intercepter" ref="aspect1"> 
      <aop:around pointcut="execution(* *..*ServiceImpl.*(..))" 
       method="serviceIntercept" /> 

     </aop:aspect> 
    </aop:config> 

<bean id="aspect1" class=Intercepter"> 

    </bean> 

public class Intercepter 

{ 
private String variable1; 

    public Intercepter() 
    { 
    } 

    public Object serviceIntercept(ProceedingJoinPoint pjp) 
     throws Throwable 
    { 
Object retVal = null; 
     //Method M1 set value of variable1 
     M1(); 
    // call actual Method on ServiceImpl 
retVal = pjp.proceed(); 
    } 

public class AServiceImpl { 
Method1(); 
Method1(){ 
call Method2 on BServiceImpl from AServiceImpl 
BServiceImpl.Method2() 
} 

} 

public class BServiceImpl { 
Method2(); 

} 

Main(){ 
// call AServiceImpl assuming it is single threaded. 
AServiceImpl() 


} 

所以序列如下

1.首先調用以從主AServiceImpl()()它被攔截和可變變量1被設置爲變量1 =「測試」 ; 2.現在調用AServiceImpl上的實際方法Method1()。

3.從方法1()再次調用BServiceImpl上的方法2(),再次截取它。以前,變量1的值設置爲「test」,現在這個時間設置爲「」。所以每當它截獲變量的值改變

那麼,編寫aop的最佳做法是什麼,以便從多線程和單線程程序中安全?

。在這種情況下,它是singleton作爲類Intercepter是單例和單線程的。所以我可以看到問題的寫作方面是單例。類似的問題可能發生在多線程程序中。可能會寫方面類爲Immutable類或者用原型替換singleton可以成爲我理解的解決方案。但是,我想獲得更多更深入的想法和信息,以及人們在他們的progaram中使用的不同方法的解決方案。

回答

0

在多線程程序中保持單身狀態的最簡單方法是使用ThreadLocal變量。

在你的情況下,你將不得不String variable1ThreadLocal<String> variable1

使用ThreadLocal時,必須注意清除不再使用的值。一個好地方通常是finally從句,如:

try { 
    variable1.set(...) 
    pjp.proceed(); 
} finally { 
    variable1.remove(); 
}