Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Thread-safe static methods

  Asked By: Sunil    Date: Jun 29    Category: Java    Views: 2661

I have a web application and I use a helper class to provide some
global static methods. This is one of them:

public static int parseIntString(String string, int defaultValue)
int value = defaultValue;
if (string == null || string.trim().length() == 0)
return value;
value = Integer.parseInt(string);
catch (NumberFormatException ex)
value = defaultValue;
return value;

Since this function is called from servlets, it is definitely accessed
by several threads at once. My question is - do I need to synchronize
it or is such method thread-safe? It does not change any class or
instance fields.



2 Answers Found

Answer #1    Answered By: Corey Brown     Answered On: Jun 29

As long as variables using in the method  are defined in the method
(i.e. not as class  member variables or anywhere outside method scope),
it is thread safe.
The code you described is thread safe.

Answer #2    Answered By: Fred Hicks     Answered On: Jun 29

And does it apply on input parameters as well? For example, if I have
something like that:

public static  void modifyHashMap(HashMap map)
map.put("key", "value");

Is it still thread safe or not? I mean, if more threads  call this
method concurently, will each of them modify its own map?

Didn't find what you were looking for? Find more on Thread-safe static methods Or get search suggestion and latest updates.