【发布时间】:2012-09-20 05:00:49
【问题描述】:
我正在使用 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 ;
}
}
我需要从四种不同的方法中调用上述方法。当我从不同的方法调用上述方法时,上述总代码正在执行。 我的要求只是一次整个方法必须执行。剩下的 3 次 整个方法不应该被执行。应该返回存储在 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
} }
【问题讨论】:
-
上面的611和529表示调用上面的行号(主叫行号)。
-
您的要求不明确。
-
@DaveNewton 我需要不止一种方法的 threadLocalRate 变量(几乎有 4 种方法)。它将具有汇率(USD -> INR)。用于查找汇率的代码应该只执行一次。剩下 3 次它不应该得到 .execute。所以我在这里使用了 ThreadLocale 概念。但它不起作用。我更新了问题。
-
好吧,您当然不需要在操作中使用它,因为操作是按请求创建的。为什么不直接将其传递给其他方法?
-
如果基于用户详细信息,这似乎很冒险,这意味着每个用户的价值可能不同。
标签: java multithreading struts2 thread-local