threads, and the lack of global data

T

ted holden

Real, real stupid question here....

Global data is the most obvious and simpleminded way for different threads
to communicate and share information; nonetheless as I understand it, Java
does not allow global data items (somebody tell me if I'm wrong about
that)...

Granted I can think of other ways of getting information to a second or
third thread, is there any sort of a GENERAL way they tell you to do that
or something viewed as a best practice or some such?
 
I

Ian A. Mason

nonetheless as I understand it, Java
does not allow global data items (somebody tell me if I'm wrong about
that)...

Yes you are wrong, a static field of a class is about as global as you
could want. Make it private and provide getters and setters, and you
have your globally accessible data item.
 
I

Ian A. Mason

Isn't a singleton just a private static field, plus some extra
stuff, like a private constructor, and a getter that does the
allocation if necessary? But yes that will work too.
 
T

ted holden

Ian said:
Yes you are wrong, a static field of a class is about as global as you
could want. Make it private and provide getters and setters, and you
have your globally accessible data item.


Thanks. That's more or less what I'd have assumed but I thought I'd put the
question out and see if there was an sort of cosmic/ultimate answer to it
which I hadn't considered. What that really says is that the security of
not having global data comes with a small pricetag in the form of a little
bit more work being required.
 
I

iamfractal

ted holden said:
Real, real stupid question here....

Global data is the most obvious and simpleminded way for different threads
to communicate and share information; nonetheless as I understand it, Java
does not allow global data items (somebody tell me if I'm wrong about
that)...

Granted I can think of other ways of getting information to a second or
third thread, is there any sort of a GENERAL way they tell you to do that
or something viewed as a best practice or some such?

Hi, Ted!

Not a stupid question at all. As you mention, global data is a
solution, but you can also pass a container for the data between the
threads involved, thus having it somewhat more encapsulated than
globally accessible by the entire appliation.

Also, and perhaps more importantly, make sure your threads synchronize
the access to the shared data, see:
http://java.sun.com/docs/books/tutorial/essential/threads/synchronization.html

..ed

www.EdmundKirwan.com - Home of The Fractal Class Composition.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,192
Latest member
KalaReid2

Latest Threads

Top