私はStrust2とHibernateを使用しています。為替レート(USDからINR)を調べなければなりません。この情報を複数の場所で使用する必要があります。この目的のために、私はこの目的のために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 ;
}
}
上記のメソッドを4つの異なるメソッドから呼び出す必要があります。上記のメソッドをさまざまなメソッドから呼び出すと、上記の合計コードが実行されます。私の要件は、メソッド全体を実行する必要があるのは1回だけです。そして、残りの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
私が何をしているのかを提案してください。上記のメソッドは、4つのメソッドから呼び出されます。2つのメソッドはActionクラスに属し、2つのメソッドは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
} }