views:

91

answers:

3

First a little background. I got a warning in NetBeans told me not to start a new thread in a constructor. I have read that the reason for that is because the new thread might start and try to reference the object started the thread before the constructor is actually done making the object.

1.) For the sake of experimentation instead of using new Thread and thread.start() I tried ExecutorService and I got no warning. Does this mean it is ok to create and start a new thread in a constructor if I use ExecutorService?

2.) Also, if I have an ExecutorService in the form of a cached thread pool will the creation of a new thread by the standard method of new Thread and thread.start() pull a thread from the cache pool (or cause it to create one if one is not available) or are those threads completely independent of the cached thread pool?

+1  A: 

1) No, it's probably just a limitation of NetBeans' static analysis. Of course it's safe to do either way if you don't leak a reference to the object currently being constructed.

Leaking a reference to an object being constructed isn't only dangerous in multi-threaded situations, either. Even if you call an external method from the constructor, passing yourself as a parameter, the method could use you inappropriately.

2) No, new always creates a new object, no exceptions. You are going around the thread pool.

Mark Peters
@Mark Peters, thanks for the good answer, but aioobe dumbed it down for me a bit more.
typoknig
+4  A: 

1) [...] Does this mean it is ok to create and start a new thread in a constructor if I use ExecutorService?

General rule: Don't leak the reference to the object being constructed (this) until it is fully constructed. That is, don't give away this to another therad in the constructor, don't add yourself as a listener from within the constructor, etc, etc... That is, never use this as a parameter to a function from within the constructor.

2) [...] will the creation of a new thread by the standard method of new Thread and thread.start() pull a thread from the cache pool [...]

No, there is no way new could have been overloaded to not create a fresh object. In such cases you will need to go through a factory method.

aioobe
@aioobe thanks, you explained both points well.
typoknig
+1  A: 

The constructor duty is just to construct an object, if you have an object that extend Thread, you shouldn't call to start() from inside the constructor, other different object should call start().

greuze