我正在使用 Strust2 和 Hibernate。我必须找出货币汇率(美元兑印度卢比)。我需要在多个地方使用这些信息。为此,我为此目的使用ThreadLocal。
public class GetExchangeRate{
private ThreadLocal<Double> threadLocalRate = new ThreadLocal<Double>();
public double getCurrencyRate(UserDet userDet){
LOG.info("Thread id is ---------------->"+Thread.currentThread().getId());
Double currencyRate = (Double) threadLocalRate.get();
if(currencyRate == null){
LOG.info("Object does not exist");
---//my code which is used to find USD --> INR exchange rate
threadLocalRate.set(currencyRate);
}
return currencyRate ;
}
}
我需要从四种不同的方法中调用上述方法。当我从不同的方法调用上述方法时,上述总代码正在执行。我的要求是整个方法必须执行一次。剩下的总方法的三倍不应该被执行。应该返回存储在 ThreadLocal 对象中的值。
这是我的日志报告,它显示了上面的总方法已执行。
[ INFO] 2012-09-20 10:20:04,611 [CommonFormats] (CommonFormats.java:getCurrencyRate:159)
Thread id is ---------------------------->54
[ INFO] 2012-09-20 10:20:04,611 [CommonFormats] (CommonFormats.java:getCurrencyRate:163)
Object does not exist
[ INFO] 2012-09-20 10:20:49,529 [CommonFormats] (CommonFormats.java:getCurrencyRate:159)
Thread id is ---------------------------->54
[ INFO] 2012-09-20 10:20:49,529 [CommonFormats] (CommonFormats.java:getCurrencyRate:163)
Object does not exist
请建议我做错了什么。上述方法将从四个方法中调用。两个方法属于Action类,两个方法属于Service层类。
我的示例代码
//Action class
public class StrutsAction1{
public String method1(){
// my code
CommonFormats commonFormats= new CommonFormats();
System.out.println(commonFormats.getCurrencyRate());
// my code
}
public String method2(){
// my code
CommonFormats commonFormats= new CommonFormats();
System.out.println(commonFormats.getCurrencyRate());
// my code
} }
//Business class
public class BussinessLogic{
public String method1(){
// my code
CommonFormats commonFormats= new CommonFormats();
System.out.println(commonFormats.getCurrencyRate());
// my code
}
public String method2(){
// my code
CommonFormats commonFormats= new CommonFormats();
System.out.println(commonFormats.getCurrencyRate());
// my code
} }