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