Possible Duplicate:
Java: Why not to start a thread in the constructor? How to terminate?
I'm used to run FindBugs on my code in order to find bugs or bad practice. Today it complains on the fact that I'm starting a thread in a class constructor.
Is really a bad thing to do? Could you explain me why?
It is at least safe if my class is final?
EDIT:
The thread is implemented as an inner class and it only uses fields of the main class already initialized when it is started:
public final class SingletonOuter {
private static SingletonOuter ourInstance = new SingletonOuter();
public static SingletonOuter getInstance() {
return ourInstance;
}
private final SomeOtherClass aField;
private SingletonOuter() {
aField=new SomeOtherClass();
thread=new InnerThread();
thread.start();
}
private boolean pleaseStop;
private synchronized boolean askedStop(){return pleaseStop;}
public synchronized void stop(){
pleaseStop=true;
}
private final InnerThread thread ;
private class InnerThread extends Thread{
@Override public void run() {
//do stuff with aField until askedStop()
}
}
}
EDIT:
I finally move the start of thread to the getInstance method, to avoid the possibility of introducing future bugs:
public final class SingletonOuter {
private static SingletonOuter ourInstance
public static SingletonOuter getInstance() {
if (ourInstance==null){
ourInstance= = new SingletonOuter();
ourInstance.thread.start();
}
return ourInstance;
}
private final SomeOtherClass aField;
private SingletonOuter() {
aField=new SomeOtherClass();
thread=new InnerThread();
}
...