Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Object in a thread safety way

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.

like image 703
Rollerball Avatar asked May 23 '13 15:05

Rollerball


1 Answers

  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
like image 56
Adam Siemion Avatar answered Oct 11 '22 20:10

Adam Siemion