java的懒汉式_java的懒汉式

构造方法里Thread.sleep(10),模拟下类的构造过程,用多线程去getInstance(),再print(m_instance),就会发现地址值不一样了,说明构造了多个对象,这么写就是防止这种情况。其实也并不需要用DCL这种方式,饿汉模式就能避免这种情况。######嗯嗯 sleep() 要的就是这个 非常感谢######个人是这么理解的,假如有两个线程 A,B同时调用 getInstance方法,当A线程运行到代码第6行时,时间片被撤出,B线程运行getInstance方法,拿到锁之后,对变量进行赋值,这是为了防止多线程的情况下,会造成建立多个对象。######  private static LazySingleton m_instance = new LazySingleton(); 这样简单

######嗯 饿汉式单例和带有同步机制的懒汉式单例都应该没问题######如果初始化开销大,这种方式就不太好。但是一般的,这种方式比较好。我也喜欢这种方式。###### 对的 可以参考《Java concurrency in practice》16.2.4节 如果必须实现lazy initialization,可以利用JVM的lazy class loading机制。 ######额 我找找这本书######写两个线程,打个断点不就可以观察了吗?或者在 if(m_instance == null)后面sleep()几秒,如果没有双重检查,你就会看到两个线程分别分别产生了不同的对象,二者拿到的对象不是同一个,因此不能保证单例######sleep正中靶心###### Intuitively, this algorithm seems like an efficient solution to the problem. However, this technique has many subtle problems and should usually be avoided. For example, consider the following sequence of events:

Thread A notices that the value is not initialized, so it obtains the lock and begins to initialize the value. Due to the semantics of some programming languages, the code generated by the compiler is allowed to update the shared variable to point to a partially constructed object before A has finished performing the initialization. For example, in Java if a call to a constructor has been inlined then the shared variable may immediately be updated once the storage has been allocated but before the inlined constructor initializes the object.[4] Thread B notices that the shared variable has been initialized (or so it appears), and returns its value. Because thread B believes the value is already initialized, it does not acquire the lock. If B uses the object before all of the initialization done by A is seen by B (either because A has not finished initializing it or because some of the initialized values in the object have not yet percolated to the memory B uses (cache coherence)), the program will likely crash.(wiki) ######嗯嗯 就是这个意思 本来很晕 看了大家的回答 确实这段代码在java中就是错误的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值