双重检查锁定作为反模式 [英] Double-checked locking as an anti-pattern

查看:563
本文介绍了双重检查锁定作为反模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种常见的信念和多种来源(包括维基)声称此成语

There's a common belief and multiple sources (including wiki) that claim this idiom to be an anti-pattern.


  1. 在使用正确的实现方式时,在生产代码中使用它的参数是什么,使用 volatile

在多线程环境中实现延迟初始化的适当替代方法是什么?锁定整个方法可能会成为一个瓶颈,即使现代同步相对便宜,但它仍然很慢,特别是在争用。静态持有者似乎是一种语言特定的,有点丑陋的黑客(至少对我来说)。基于原子的实现似乎没有那么不同于传统的DCL,而允许多个计算或需要更复杂的代码。例如,Scala是仍然使用 DCL实现延迟

What are the appropriate alternatives for implementing lazy initialization in a multithreaded environment ? Locking the whole method may become a bottleneck and even while modern synchronization is relatively cheap, it's still much slower especially under contention. Static holder seems to be a language-specific and a bit ugly hack (at least for me). Atomics-based implementation seems not be so different from traditional DCL while allowing multiple calculations or requires more complicated code. For example, Scala is still using DCL for implementing the lazy values while proposed alternative seems to be much more complicated.


推荐答案

t使用双重锁定。永远。这是行不通的。不要试图找到一个黑客来使它工作,因为它可能不是在以后的JRE。

Don't use double checked locking. Ever. It does not work. Don't try to find a hack to make it work, because it may not on a later JRE.

据我所知,没有其他保存方式延迟初始化比锁定整个对象/同步。

As far as I know, there is no other save way for lazy initialization than locking the whole object / synchronizing.

synchronized (lock) {
  // lookup

  // lazy init
}



对于单例,静态持有者

For singletons the static holder (as @trashgod mentioned) is nice, but will not remain single if you have multiple classloaders.

如果在多类加载器环境中需要一个延迟的单例,请使用 ServiceLoader

If you require a lazy singleton in a multi-classloader environment, use the ServiceLoader.

这篇关于双重检查锁定作为反模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆