Creating Object in a thread safety way

前端 未结 8 2239
再見小時候
再見小時候 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:16

    1. Let us assume, you have such class:

      class Sync {
          public Sync(List 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 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

提交回复
热议问题