Creating Object in a thread safety way

前端 未结 8 2236
再見小時候
再見小時候 2021-02-06 12:50

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

Warning: When constructing an object that will b

8条回答
  •  盖世英雄少女心
    2021-02-06 13:32

    Lot of good data here but I thought I'd add some more information.

    When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely.

    While you are constructing the object, you need to make sure that there is no way for other threads to access this object before it can be fulling constructed. This means that in a constructor you should not, for example:

    • Assign the object to a static field on the class that is accessible by other threads.
    • Start a thread on the object in the constructor which may start using fields from the object before they are fulling initialized.
    • Publish the object into a collection or via any other mechanisms that allow other threads to see the object before it can be fulling constructed.

    You might be tempted to add the following line to your constructor:

       instances.add(this);
    

    So something like the following is improper:

      public class Foo {
          // multiple threads can use this
          public static List instances = new ArrayList();
          public Foo() {
             ...
             // this "leaks" this, publishing it to other threads
             instances.add(this);
             ...
             // other initialization stuff
          }
          ...
    

    One addition bit of complexity is that the Java compiler/optimizer has the ability to reorder the instructions inside of the constructor so they happen at a later time. This means that even if you do instances.add(this); as the last line of the constructor, this is not enough to ensure that the constructor really has finished.

    If multiple threads are going to be accessing this published object, it must be synchronized. The only fields you don't need to worry about are final fields which are guaranteed to be finished constructing when the constructor finishes. volatile fields are themselves synchronized so you don't have to worry about them.

提交回复
热议问题