美国上市公司,专注Java培训21年

关于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是与线程绑定的,所以是线程安全的,并且也在官网的线程安全介绍中得到了证实。

#/JacksonBestPracticeThreadSafety

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).

第一个顾虑在看完下面这篇文章后,得到了解决方法:

#/developerworks/cn/java/j-jtp06197.html

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 关键字的配合。


【免责声明】本文部分系转载,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,如涉及作品内容、版权和其它问题,请在30日内与我们联系,我们会予以重改或删除相关文章,以保证您的权益!

Java开发高端课程免费试学

大咖讲师+项目实战全面提升你的职场竞争力

  • 海量实战教程
  • 1V1答疑解惑
  • 行业动态分析
  • 大神学习路径图

相关推荐

更多
  • 在Java中10种常见设计模式详细介绍
  • Java开发与Python开发优劣比较
    Java开发与Python开发优劣比较
    Java开发与Python开发优劣比较,java属于高大上,适合12306这种有钱的金主,同样的项目要是用java做的,就能唬来成倍的钱,没钱搞java在eclipse吭哧吭哧地编译完项目以后,在七八屏的堆栈信息里,不停上翻下翻象捡芝麻一样找底哪里出错了,python属于小而美,适合做一些内聚性很强的工具,用来当锤子,榔头使唤。 详情>>

    2018-10-25

  • 关于JAVA单例的问题
  • 你是否对java语言有正确的认识
  • Java开班时间

    收起