简体   繁体   English

在多个线程上同步var实例化

[英]Synchronizing var instantiation upon multiple threads

I'm trying to sync a var instantiation like this one: 我正在尝试像这样同步一个var实例:

Object o = new Object();
String s = null;

void getS() {
  if (s != null) {
    return s;
  }
  // multiple threads stopping here
  // maybe using readwritelock? write.lock?
  syncronize(o) {
    // if previous thread stopped by sync block
    // completed before, bypass this
    if (s != null) {
      return s;
    }

    // no one before, instantiate s
    s = "abc";
  }
  return s; 
}

Is there a better way to handle a single time instantiation of var s? 有没有更好的方法来处理var的单个时间实例化? Maybe using locks? 也许使用锁?

Declare s volatile 声明s挥发性

volatile String s;

and we'll get a classic double-checked locking design pattern implementation. 我们将获得经典的双重检查锁定设计模式实现。 Patterns are formalized best practices so you dont need to try and further improve this code. 模式是形式化的最佳实践,因此您无需尝试进一步改进此代码。

BTW the example with lazy String initialization makes no sense, it should be an expensive to create Object 顺便说一句,使用惰性字符串初始化的示例没有任何意义,创建对象应该是昂贵的

The simplest to write: 最简单的写法:

private Foo foo;
public synchronized Foo getFoo() {
    if (foo == null) {
        foo = new Foo();
    }
    return foo;
}

The downside is that you have synchronization happen every time you access this property, even though synchronization is only needed the first time. 不利之处在于,即使只在第一次时才需要同步,每次访问此属性时都会发生同步。

Google "double checked locking in java" for lots of information about ways that you can accomplish the same thing, but with less locking (and therefore potentially better performance). Google对Java进行了“双重检查锁定”,以获取有关可以完成相同任务的方式的大量信息,但锁定较少(因此可能会提高性能)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM