[concurrency-interest] Starting a Thread within a constructor, what can go wrong?

Marco Villalobos mvillalobos at kineteque.com
Fri Dec 10 20:30:02 EST 2010


QUESTION:

Can somebody please give me guidance on how I could possibly create a
suite of test cases that run in TestNG or JUnit that can prove the
thread unsafeness of this bad practice?

BACKGROUND

I'm trying to convince my colleague that starting a thread within a
constructor compromises thread safety.

I understand that, "publishing objects before they are fully
constructed can compromise thread safety."

But I would like an elaboration on how it compromises thread safety?

I understand that publishing the "this" reference would break
encapsulation, allowing other classes and threads to potentially
change the state of my object in an unthread safe manner.

But more specifically, what are the side affects of an object not
being fully constructed, yet published through a thread.start in a
constructor.

Here is an example of how "not to do things".

public class DontDoThis {

  public synchronized void mutateMe() {
      // ... I'm mutating this...
  }

  public final Thread t;

  public DontDoThis() {
      t = new Thread(new Runnable() {
          public void run() {
              mutateMe();
          }
      });
      t.start();   //     BAD BAD BAD Don't do this.
  }
}

Can somebody please give me guidance on how I could possibly create a
suite of test cases that run in TestNG or JUnit that can prove the
thread unsafeness of this bad practice?

I want to make a short presentation on the issue.  If I provide a
compilable and running test case, that would be amazing :)

-Marco


More information about the Concurrency-interest mailing list