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

Joe Bowbeer joe.bowbeer at gmail.com
Fri Dec 10 22:24:20 EST 2010


Marco,

In addition to the other excellent replies, I'll add my $0.02

The original SwingWorker, which is a class designed for subclassing, started
its worker thread in its constructor and this led to many problems in
practice.

Another problem with starting a thread in a constructor is that it is not
expected.  My expectation is that a constructor merely creates.  If I want
action, I'll call a method.

In addition, I would ask why you're even creating a thread?  Consider
creating a task instead and using an executor.

On Fri, Dec 10, 2010 at 5:30 PM, Marco Villalobos wrote:

> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20101210/0bc5d030/attachment.html>


More information about the Concurrency-interest mailing list