Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changed the CS to emphasize that there is nothing wrongwith creating a thread in the constructor; however, it should not be started

...

Code Block
bgColor#FFcccc
class RoutineThreadStarter implements Runnable {
  public RoutineThreadStarter() {
    Thread thread = new Thread(this);
    thread.start();
  }

  public void run() {
    // thread execution code...
  }
}

Wiki Markup
This allows the new thread to access the {{this}} reference of the current object \[[Goetz 02|AA. Java References#Goetz 02], [Goetz 06|AA. Java References#Goetz 06]\].

...

In this compliant solution, even though the thread execution is done in a public method, rather than in the constructorcreated in the constructor, it is not started until its start() method is called from method startThread() Goetz 02, Goetz 06.

Code Block
bgColor#ccccff
class RoutineThreadStarter implements Runnable {
  Thread thread;

  public void startThreadThreadStarter() {
    Thread thread = new Thread(this);
  }

  public void startThread() {    
    thread.start();
  }

  public void run() {
    // thread execution code
  }
}

It is safe to create the thread in the constructor as long as it is not started until object construction is over.

Risk Assessment

Allowing the this reference to escape may result in improper initialization and runtime exceptions.

...