...
| Code Block | ||
|---|---|---|
| ||
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 | ||
|---|---|---|
| ||
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.
...