This discussion is archived
2 Replies Latest reply: May 25, 2008 2:03 PM by 807591 RSS

Static variables + Threads

802210 Newbie
Currently Being Moderated
Hello I want to ask if I use a static variable in JAVA, and threads, for example if the thread 1 come and put a static variable = 4, then all the others threads that access to that variable will see variable = 4 right?

And if I don't use static the data will not be share. All the threads will have his own instance of the variable?

Thanks
  • 1. Re: Static variables + Threads
    807591 Newbie
    Currently Being Moderated
    GonzaloP wrote:
    Hello I want to ask if I use a static variable in JAVA, and threads, for example if the thread 1 come and put a static variable = 4, then all the others threads that access to that variable will see variable = 4 right?
    Not necessarily. Threads can store cached versions of classes, as I recall.

    If you want the data to be viewable by all, make it synchronized. If you don't care about the timing too much, just marking the field volatile might be sufficient.
    And if I don't use static the data will not be share. All the threads will have his own instance of the variable?
    No. You can easily pass a single object to multiple threads. It doesn't have to be static.

    Try to avoid using static too much. You end up with code that's not really object-oriented, and you lose all the benefits of OOP and using a language that supports OOP.
  • 2. Re: Static variables + Threads
    807591 Newbie
    Currently Being Moderated
    What thread you're in really doesn't make any difference to what values etc. you see in fields. Each thread has it's own method invocations and local variables but that all.