這個問題由最開始使用JACKSON JSON而衍生出來
最開始的寫法
Java代碼
public final class JacksonJsonMapper {
static volatile ObjectMapper objectMapper = null;
private JacksonJsonMapper(){}
public static ObjectMapper getInstance(){
if (objectMapper==null){
objectMapper = new ObjectMapper();
}
return objectMapper;
}
}
在此期間
後再看了源碼後
Jackson follows thread
Factories (ObjectMapper
Reader/writer instances (like JsonParser and JsonParser) are not thread
All transformer objects (custom serializers
第一個顧慮在看完下面這篇文章後
l
Java代碼
public final class JacksonJsonMapper {
static volatile ObjectMapper objectMapper = null;
private JacksonJsonMapper(){}
public static ObjectMapper getInstance(){
if (objectMapper==null){
synchronized (ObjectMapper
if (objectMapper==null){
objectMapper = new ObjectMapper();
}
}
}
return objectMapper;
}
}
文章中詳細說明了關鍵字 volatile 是在讀取所申明的對象時
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27515.html