0

It is said threads should NEVER be started in constructors, but I am not sure how this reference escapes the Test constructor in this case. I looked at the underlying Thread.java and I cannot figure this out.

class Test {

    static MyThread thread;

    public Test() {

        thread = new MyThread();
        thread.start();

    }

}

class MyThread extends Thread {

    public void run() {

        //do stuff

    }

}

Thanks for the help.

thread = new MyThread(); would call Thread super constructor:

public Thread() {
    init(null, null, "Thread-" + nextThreadNum(), 0);
}

I do not see a reference getting away.

Charles
  • 50,943
  • 13
  • 104
  • 142
jn1kk
  • 5,012
  • 2
  • 45
  • 72

1 Answers1

5

this can only escape if the thread references this (eg, if it's an inner class)

Your thread does not reference this, so this is not an issue.

However, constructing an object is generally expected to be side-effect-free; this is not a good idea.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • But books I read say you should never do this. Is this case ok then? EDIT: seems so seeing your edit. – jn1kk Jan 22 '13 at 15:07
  • @jsn: The books are correct; you should not do this, but not for that reason. – SLaks Jan 22 '13 at 15:09