Why creating objects inside constructors is a bad move

So recently I’ve started studying how to create multi-threaded applications and one of the problems I stumbled upon is the “this” reference escaping. What it means is that you pass the reference of an object that isn´t fully constructed to another piece of code in your application that will use that object. As with the majority of multi-threaded bugs, this can have subtle consequences ranging from all working fine to application crashes.

One of the easiest ways to show this problem is by creating new objects in the constructor. If we are not really carefull, we may let the this reference escape the constructor before this object is fully created. This causes problems because another thread may start using the object before the constructor completes. A simple example is creating a thread in the constructor like so:

public Xpto()
    list = new LinkedList<int>();
    new Thread(this.Get).Start();

public int Get()
    return list.GetFirst();

This way, the compiler may decide to reorder the two “instructions” and make the thread call the method this.Get() before the list is created.

Please note that the Thread.Start() has volatile properties meaning that everything related to the thread is garanteed to happen before it starts. However the thread only needs the “this” reference and dosen’t use the list directly. So from the point-of-view of the compiler, he is allowed to reorder the instructions as he pleases and so may decide that the call to the list constructor should occur AFTER the thread starts (since by this time the “this” reference already exists)!

This entry was posted in Knowledge and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s