No Thread.start() In Constructor
ID |
java.no_thread_start_in_constructor |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
concurrency, reliability |
Rationale
Starting a thread from a constructor exposes a partially-constructed object to the new thread. The new thread may observe fields that have not been initialized yet, leading to subtle and hard-to-reproduce concurrency bugs.
// Bad - thread may see uninitialized fields
public class Worker {
private final List<String> data;
public Worker() {
this.data = new ArrayList<>();
new Thread(this::process).start(); // data might not be visible to the thread
}
}
Remediation
Separate object construction from thread start. Use a factory method or a dedicated init() method to start the thread after the object is fully constructed.
// Good - start thread after construction
public class Worker {
private final List<String> data;
public Worker() {
this.data = new ArrayList<>();
}
public void start() {
new Thread(this::process).start();
}
}