Assume I have an abstract class with all static methods should I synchronize all my static methods. What will happen if I don't?
There are other ways besides using
synchronized to make a
static method thread-safe, but they are more complicated. For instance, you generally should use local variables instead of class variables to be sure each thread gets its own copy. You also have to consider any calls to methods in the
java library classes found in java.lang, java.io, etc. Some of these methods are inherently thread-safe, some use
synchronized, and some are not thread-safe.
The consequence of having multiple threads calling a method that is not thread-safe is the random occurrance of incorrect results depending on when each thread gets control. If three threads are each incrementing a shared variable, you could wind up adding one, two, or three to the variable. Remember that increment is implemented as separate load, add 1, and store operations. You could get load(thread 1) add1(1) load(2) add1(2) load(3) add1(3) store(1) store(2) store(3). Think about all the combinations and the answers you would get.