以线程安全的方式创建对象 [英] Creating Object in a thread safety way

查看:129
本文介绍了以线程安全的方式创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直接从网站,我遇到了有关创建对象的以下描述线程安全。


警告:当构造一个将在
线程之间共享的对象时,对象不会
泄漏过早。例如,假设您要维护一个List
,称为包含类的每个实例的实例。你可能是
试图添加以下行到你的构造函数:



instances.add(this);



但是其他线程可以在
构造对象之前使用实例来访问对象。


是否有人能够用其他词语或另一个更容易理解的例子来表达相同的概念?



提前感谢。

解决方案


  1. 让我们假设你有这样的类:

      class Sync {
    public Sync(List< Sync> list){
    list.add(this);
    // switch
    //实例初始化代码
    }

    public void bang(){}
    }


  2. 并且你有两个线程(线程#1和线程#2),它们都有一个引用 List< Sync>现在线程#1创建了一个新的同步实例。

  3. 作为参数提供对列表实例的引用:

      new同步(列表); 


  4. 执行行 // switch Sync 构造函数中有一个上下文切换,现在线程#2正在工作。


  5. #2执行此类代码:

      for(Sync elem:list)
    elem.bang


  6. 线程#2调用 bang()在第3点创建的实例上,但此实例尚未准备好使用,因为此实例的构造函数尚未完成。


因此,在调用构造函数时,必须非常小心,




    <并在实现构造函数时传递对几个线程之间共享的对象的引用
  • 。您必须记住,提供的实例可以在几个线程之间共享


Directly from this web site, I came across the following description about creating object thread safety.

Warning: When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the following line to your constructor:

instances.add(this);

But then other threads can use instances to access the object before construction of the object is complete.

Is anybody able to express the same concept with other words or another more graspable example?

Thanks in advance.

解决方案

  1. Let us assume, you have such class:

    class Sync {
        public Sync(List<Sync> list) {
            list.add(this);
            // switch
            // instance initialization code
        }
    
        public void bang() { }
    }
    

  2. and you have two threads (thread #1 and thread #2), both of them have a reference the same List<Sync> list instance.

  3. Now thread #1 creates a new Sync instance and as an argument provides a reference to the list instance:

    new Sync(list);
    

  4. While executing line // switch in the Sync constructor there is a context switch and now thread #2 is working.

  5. Thread #2 executes such code:

    for(Sync elem : list)
        elem.bang();
    

  6. Thread #2 calls bang() on the instance created in point 3, but this instance is not ready to be used yet, because the constructor of this instance has not been finished.

Therefore,

  • you have to be very careful when calling a constructor and passing a reference to the object shared between a few threads
  • when implementing a constructor you have to keep in mind that the provided instance can be shared between a few threads

这篇关于以线程安全的方式创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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