Should static method in a utility class be synchronized

Hi. I have searched google with various possible word combinations to no avail. My question isShould static method in a utility class be synchronized? For example, java.lang.Character class has a method isWhiteSpace() which is a static method. Suppose this method is being called simulatneously from two classes, could it pose a potential problem given that the method is static?From my understanding, a static method would be shared by all objects calling it. So without it being synchronized, is there a possibility of its internal data stack being compromised when two different objects are using it at the same time.

[642 byte] By [kozmic.blues] at [2007-9-30 12:53:06]
# 1
Depends on if the static method has any side effects. The Chararcter.isWhiteSpace() method has no side effect, so it doesn't have to be a synchronized method. But even if a static method has side effects it doesn't have to be synchronized to thread safe, there are other ways.
jsalonen at 2007-7-4 17:14:41 > top of Java-index,Administration Tools,Sun Connection...
# 2

To be more specific, suppose the static method is not making use of any static variables etc. i.e. the only variables it uses are local variables. So, does that mean that all threads making use of that method get their own stack for executing the method or do they share the stack? Also, could u please elaborate on the side-effects that u r talking about becoz the situations in which a static method needs or needs not to be synchroznied is what I mean to ask.

Regards.

kozmic.blues at 2007-7-4 17:14:41 > top of Java-index,Administration Tools,Sun Connection...
# 3

Every thread has a stack of its own and its own copies of local variables, if a static method uses only locals it doesn't have to be synchronized.

Using lazy initialization with the singleton pattern is a good example of side effects. Examine this code:class Singleton {

static Singleton instance;

static Singleton getInstance() {

if (instance == null) instance = new Singleton();

return instance;

}

// don't allow other classes to create an instance

private Singleton() {}

}

Now what happens if two threads simultaneously enter the getInstance method and both find the value of the "instance" variable null in the if-condition? You end up creating an instance of the class twice, which is not what you want. This can be solved by writing the method declaration as "synchronized static Singleton getInstance()" so no two threads can enter the method simultaneously.

jsalonen at 2007-7-4 17:14:41 > top of Java-index,Administration Tools,Sun Connection...
# 4
Thanx.
kozmic.blues at 2007-7-4 17:14:41 > top of Java-index,Administration Tools,Sun Connection...