Keyword Static and Thread Safety

Please tell me whether Static methods or variable or blocks are thread safe or not ?Thanks
[104 byte] By [narocksa] at [2007-10-2 15:44:59]
# 1

Static blocks will only be executed once, by the first thread that accesses the class so they're pretty safe.

As to fields etc., it's not a matter of static vs. instance, it's a matter of how you use them. If a variable can be changed by more than one thread that will run in parallel then you have to think about the possible sequences of events. For example it's not safe to increment a variable, because between picking up the old value and putting back the +1 value some other thread might do the same thing. The result would be only one of the increments would happen.

Where there are problems you'll have to think about using synchronized methods or blocks.

Variables that don't change are fine. Local variables are fine.

malcolmmca at 2007-7-13 15:38:36 > top of Java-index,Java Essentials,Java Programming...
# 2
The OP created 3 threads with the same question. http://forum.java.sun.com/thread.jspa?threadID=720698Kaj
kajbja at 2007-7-13 15:38:36 > top of Java-index,Java Essentials,Java Programming...