關(guān)于使用JAVA單例的問題分析
這個(gè)問題由最開始使用JACKSON JSON而衍生出來,因?yàn)楣倬W(wǎng)上建議將ObjectMapper作為全局變量使用從而提高效率,所以,我們項(xiàng)目里面使用了單例,在使用單例的時(shí)候,我們無可厚非的考慮了資源在使用時(shí)是否要保證互斥的情況。最開始的寫法:
Java代碼
public final class JacksonJsonMapper {
static volatile ObjectMapper objectMapper = null;
private JacksonJsonMapper(){}
public static ObjectMapper getInstance(){
if (objectMapper==null){
objectMapper = new ObjectMapper();
}
return objectMapper;
}
}
在此期間,我考慮了兩個(gè)問題,并與團(tuán)隊(duì)中的另外一個(gè)兄弟發(fā)生了激烈的討論:
1、在使用getInstance()方法的時(shí)候,是否要使用synchronized關(guān)鍵字。
2、在使用objectMapper.writeValueAsString(object)時(shí),因?yàn)榇朔椒ǚ庆o態(tài)方法,在此方法內(nèi)是否會(huì)使用到對(duì)象自有的屬性,而在并發(fā)的時(shí)候出現(xiàn)前者屬性被后者覆蓋的問題。
后再看了源碼后,排除了第二個(gè)顧慮,ObjectMapper是與線程綁定的,所以是線程安全的,并且也在官網(wǎng)的線程安全介紹中得到了證實(shí)托福代考 托福答案
Jackson follows thread-safety rules typical for modern factory-based Java data format handlers (similar to what, say, Stax or JAXP implementations do). For example:
Factories (ObjectMapper, JsonFactory) are thread-safe once configured: so ensure that all configuration is done from a single thread, and before instantiating anything with factory.
Reader/writer instances (like JsonParser and JsonParser) are not thread-safe -- there is usually no need for them to be, but if for some reason you need to access them from multiple threads, external synchronization is needed
All transformer objects (custom serializers, deserializers) are expected to be stateless, and thereby thread safe -- state has to be stored somewhere outside instances (in ThreadLocal or context objects passed in, like DeserializationContext).雅思代考 雅思答案
第一個(gè)顧慮在看完下面這篇文章后,得到了解決方法:
Java代碼
public final class JacksonJsonMapper {
static volatile ObjectMapper objectMapper = null;
private JacksonJsonMapper(){}
public static ObjectMapper getInstance(){
if (objectMapper==null){
synchronized (ObjectMapper.class) {
if (objectMapper==null){
objectMapper = new ObjectMapper();
}
}
}
return objectMapper;
}
}
文章中詳細(xì)說明了關(guān)鍵字 volatile 是在讀取所申明的對(duì)象時(shí),會(huì)要從內(nèi)存中進(jìn)行同步,但是不會(huì)對(duì)寫時(shí)起作用,所以,還是需要synchronized 關(guān)鍵字的配合。
posted on 2013-03-12 20:39 好不容易 閱讀(351) 評(píng)論(0) 編輯 收藏