Re: concurrency, threads and objects
- From: "Chris Uppal" <chris.uppal@xxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Wed, 15 Nov 2006 16:28:10 -0000
Tom Forsmo wrote:
[...] 2) when
reading the name of the thread all threads are named the same.
The name comes from the instance of Thread, and can be set
independently of the Runnable object that each thread executes.
I tried this but it did not work properly. What I did was this:
thr = new Thread[opt.getThreads()];
for(int i=0; i<opt.getThreads(); i++) {
thr[i] = new Thread(this);
thr[i].setName("thread num: " + i);
thr[i].start();
}
But I found out, just now, that if I use setName() inside run(), then it
works ok, why is that? the object is created outside run so changing its
state there should be ok, unless the object is reinitialised when run()
starts to execute.
I can't think of any reason why setName() wouldn't work. I admit I haven't
tested it, but I can't see anything odd in the source. I suspect that it's an
artefact of whatever you are using to "see" the Thread's names.
But why use setName() at all ? It seems easier just to pass the correct names
to the Threads' constructors in the first place.
If I use 100
threads, I would create 100 ClassA objects, which means I would have 100
ClassA objects and 100 Thread objects.
So what ?
;-)
Think of it like this. If those 100 objects which implement Runnable are
genuinely unnecessary, then they must be effectively stateless in that none of
the processing in any thread depends on the state of its Runnable object -- in
which case there is no reason not to use the same Runnable for every Thread.
But, going further, if they are /actually/ stateless, or nearly so, then they
are so cheap that they cost much less (in space and time) than the Thread
itself, and will almost certainly cost less even than the thread's /name/, so
there is no reason to go to the (cognitive) effort of reusing the same object.
Just create 100 of 'em -- you can afford it.
OTOH, if the Runnables' states /do/ affect the subsequent execution, then you
obviously can't get away without having separate objects...
BTW, the most common case is that each thread /is/ parameterised in some way
(which Socket to read from, which array to process, which Snoggle to
delaminate(), ....) and the Runnable objects are the natural place to put that
information.
-- chris
.
- Follow-Ups:
- Re: concurrency, threads and objects
- From: Tom Forsmo
- Re: concurrency, threads and objects
- References:
- concurrency, threads and objects
- From: Tom Forsmo
- Re: concurrency, threads and objects
- From: Chris Uppal
- Re: concurrency, threads and objects
- From: Tom Forsmo
- concurrency, threads and objects
- Prev by Date: Re: Problem with socket permission
- Next by Date: Bogus NullPointerExceptions
- Previous by thread: Re: concurrency, threads and objects
- Next by thread: Re: concurrency, threads and objects
- Index(es):