On 03/02/2012 12:18 PM, x wrote:
Knute Johnson pisze:
I'm having a problem in some production code that I can't figure out.
Can you please describe the usage of your class ?
I'm rather puzzled about having a Thread object inside a Runnable.
The issue would be what's used inside the 'run()' method, not just
what fields the class has.
I agree that the 'thread' variable's scope is wrong - it should be
local to 'start()', not an instance member. But at the moment that's
not causing any outright harm.
makes it is extremely easy to have TWO threads accessing private
is rarely a good idea. (yes, I have recreated it :-)
His class spawns one thread per instance. The main thread doesn't use
the mutable fields. The only common access of note is the 'runFlag'
mechanism, which is bog-standard in his code. The 'thread' member is
not referenced within 'run()'. I'm not sure why all his other instance
variables are 'volatile', but at first blush I don't see a problem
with his synchronization safety.
You need to be specific about the trouble you claim you found. Show us
where, because I don't see danger coming from the areas you cited.
Consider the following scenario:
SportsWinClient swc = new SportsWinClient();
(this exact code is unlikely to be present, but if the swc variable is
passed around, someone, in a code far far away, may start the swc in a
new thread. Simply because it's a Runnable.)
That is why I'm asking about the usage scenario.
What exactly is the point of the public start() method? I must say it
suspicious to me.
It's also bog standard, and bog simple. Its purpose is to start the
Is it standard... well, I'm not sure. As far as I know, the most typical
thing to do would be to create a Runnable object (containing ONLY the
task logic), and a separate Thread object:
Runnable myRunnable = new MyRunnable(...);
Threat t = new Thread(myRunnable);
public class Client
public static void main(String args)
I'm not sure what your argument is. It is easy enough either way to
create or start numerous examples. I don't and I won't and your
scenario wouldn't prevent that either. And if the Thread is started
more than once it throws and exception.