熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

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

2022-06-13   來源: 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;

  }

  }

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

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

  在使用objectMapperwriteValueAsString(object)時因為此方法非靜態方法在此方法內是否會使用到對象自有的屬性而在並發的時候出現前者屬性被後者覆蓋的問題

  後再看了源碼後排除了第二個顧慮ObjectMapper是與線程綁定的所以是線程安全的並且也在官網的線程安全介紹中得到了證實

  Jackson follows threadsafety rules typical for modern factorybased Java data format handlers (similar to what say Stax or JAXP implementations do) For example:

  Factories (ObjectMapper JsonFactory) are threadsafe 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 threadsafe 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 (ObjectMapperclass) {

  if (objectMapper==null){

  objectMapper = new ObjectMapper();

  }

  }

  }

  return objectMapper;

  }

  }

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


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26577.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.