确保在访问成员变量之前完成初始化方法 [英] Ensuring initialization methods complete before member variable is accessed

查看:92
本文介绍了确保在访问成员变量之前完成初始化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以确保通过一个线程 volatile static 成员变量上运行的一组方法能够完成并在其他线程之前完成访问此成员变量?我正在尝试类似的方法,但是我不确定是否可以使用.

Is there a way of ensure that a set of methods operating on a volatile static member variable via one thread will be done and over with before other threads access this member variable? I am trying something like this, but I am not sure if it would work.

public class MyClass
{
  private static final Object lock = new Object();
  public static volatile MyObj mo; //assume null will be checked before access

  public static void initialize()
  {
    if (mo == null)
    {
      synchronized(lock)
      {
        mo = new MyObj();
        mo.doInit();
        mo.doMoreInit();
      }
    }
  }
}

推荐答案

您需要将mo的赋值延迟到之后被调用所有方法(即,使用局部变量然后赋值) mo作为最后步骤).

You need to delay the assignment of mo until after all the methods are called (i.e. use a local variable and then assign mo as the last step).

请注意,您实际上是在实施双重检查锁定(尽管使用volatile使其可以正确"工作).您需要在同步块中的 中再次检查mo是否为空.

Note, you are essentially implementing double checked locking (although using volatile makes it work "correctly"). you need to check mo for null again within the synchronized block.

此外,还有其他一些(更好一些)的模式,例如使用类初始化模式来管理同步. http://en.wikipedia.org/wiki/Singleton_pattern

also, there are some other (somewhat better) patterns for this like using the class initialization pattern for managing the synchronization. Pretty much every pattern imaginable is detailed here http://en.wikipedia.org/wiki/Singleton_pattern

这篇关于确保在访问成员变量之前完成初始化方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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