views:

165

answers:

5

I have a question...
Can we call thread_object.start() from within a constructor ?
Is this approach a good idea ?

Thanks.

A: 

I would suggest to start the thread outside, instead of calling from Constructor. In constructor you should be doing only initialization stuff.

Phanindra
+5  A: 

You can do that, but it is considered as bad practice. There is one paragraph about starting Threads in constructors in this article.

AS nicerobot stated in the comments, your question seem to be a duplicate of this. Have a look at Heath Borders answer there.

Nils Schmidt
@Nils: The article only points out the risks in exposing 'this' reference when the object is not in a consistent state yet. In the case of threads, you can do it safely in the ctor by creating a non-inner-class thread, and providing it with the data it needs for running (and not with 'this' reference).
Eyal Schneider
Excellent! Reference escaping can is not thread-safe!
Loop
+1  A: 

It's a bad practice, since you cannot be sure that the object is fully initialized. Even if you call the start() method at the end of the constructor it may result in a mess.

Be aware that the processor can do things out of order:

1: MyObject(){
2:  aVariable = anyValue;
3:  this.start();
4: }

The processor is free to execute line 3 before line 2 since they aren't related (in a single threaded fashion), so you could end up with uninitalized variables (even final ones), and other unexpected stuff.

Hardcoded
+2  A: 

Just out of interest - why do you extend Thread? Why not implement Runnable instead, you get more flexibility (e.g. can be executed within a thread you create or an ExecutorService, which is the preferred method).

+1 for implementing runnable and the Java 5 concurrency APIs!
justkt
A: 

As long the thread you're starting doesn't have a reference to this then you're okay. If the thread does have a reference to this (either passed to the thread of indirectly via an inner class) then it's a bad idea to start it from the constructor as the object isn't fully initialized.

Steve Kuo