Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: correscted references, added JLS quote

...

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]\].

Compliant Solution (thread)

Wiki Markup
In this compliant solution, even though the thread is created in the constructor, it is not started until its {{start()}} method is called from method {{startThread()}} \[[Goetz 02
, Goetz 06.
|AA. Java References#Goetz 02]\], \[[Goetz 06|AA. Java References#Goetz 06]\].

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

  public ThreadStarter() {
    thread = new Thread(this);
  }

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

  public void run() {
    // ...
  }
}

Wiki Markup
It is safe to create the thread in the constructor as long as it is not started until object construction is over. This is because "A call to start() on a thread happens-before any actions in the started thread." \[[JLS 05|AA. Java References#JLS 05]\]. 

Risk Assessment

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

...