• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static method

 
Paul Christoph
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a static utility method:

public static String formatForDisplay(String s)
{
StringBuffer buffer = new StringBuffer("Value: ");

if (s != null) buffer.append(s);
else buffer.append("Empty");

return buffer.toString();
}

This is in a web application so there are multiple threads that could access it.

Do I need to synchronize this method to prevent an incorrect value from being returned?
 
Satish Chilukuri
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. Since you are using a local variable, each thread gets its own copy of that variable. There is no possibility of multiple threads accessing the same instance.
 
Paul Christoph
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, that is what I thought and what my test cases show, but I was not sure if it held in all cases. What you said makes sense.
 
Henry Wong
author
Sheriff
Posts: 22516
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Satish Chilukuri:
No. Since you are using a local variable, each thread gets its own copy of that variable. There is no possibility of multiple threads accessing the same instance.


Just to provide more clarification (and because I am being anal ) ...

The object referred to by the local variable should also not "escape" the method. It is theoretically possible for the method to call another method, which stores the object in some common area, which can be accessed by another thread, etc.

In this case, it is obvious that the string buffer can't escape, and hence, there is "no possibility of multiple threads access the same instance".

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!