中文JAVA技術平等自由協作創造

          Java專題文章博客和開源

          常用鏈接

          統計

          最新評論

          關于使用JAVA單例的問題分析

            這個問題由最開始使用JACKSON JSON而衍生出來,因為官網上建議將ObjectMapper作為全局變量使用從而提高效率,所以,我們項目里面使用了單例,在使用單例的時候,我們無可厚非的考慮了資源在使用時是否要保證互斥的情況。

            最開始的寫法:

            Java代碼

            public final class JacksonJsonMapper {

            static volatile ObjectMapper objectMapper = null;

            private JacksonJsonMapper(){}

            public static ObjectMapper getInstance(){

            if (objectMapper==null){

            objectMapper = new ObjectMapper();

            }

            return objectMapper;

            }

            }

            在此期間,我考慮了兩個問題,并與團隊中的另外一個兄弟發生了激烈的討論:

            1、在使用getInstance()方法的時候,是否要使用synchronized關鍵字。

            2、在使用objectMapper.writeValueAsString(object)時,因為此方法非靜態方法,在此方法內是否會使用到對象自有的屬性,而在并發的時候出現前者屬性被后者覆蓋的問題。

            后再看了源碼后,排除了第二個顧慮,ObjectMapper是與線程綁定的,所以是線程安全的,并且也在官網的線程安全介紹中得到了證實托福代考 托福答案

            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).雅思代考 雅思答案

            第一個顧慮在看完下面這篇文章后,得到了解決方法:

            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;

            }

            }

            文章中詳細說明了關鍵字 volatile 是在讀取所申明的對象時,會要從內存中進行同步,但是不會對寫時起作用,所以,還是需要synchronized 關鍵字的配合。

          posted on 2013-03-12 20:39 好不容易 閱讀(377) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          PK10開獎 PK10開獎
          主站蜘蛛池模板: 乌鲁木齐市| 通山县| 乾安县| 泰兴市| 棋牌| 博白县| 阜平县| 余江县| 剑阁县| 武定县| 出国| 高碑店市| 江门市| 洪江市| 双峰县| 嵊州市| 天台县| 东乌| 久治县| 南丹县| 肥西县| 宁强县| 武夷山市| 宝坻区| 黔南| 岱山县| 宜川县| 临汾市| 巢湖市| 西昌市| 连山| 海兴县| 宿迁市| 邵阳市| 崇左市| 宁远县| 平邑县| 万载县| 灵石县| 澜沧| 昌宁县|