aspose file tools*
The moose likes Java in General and the fly likes using static methods question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "using static methods question" Watch "using static methods question" New topic
Author

using static methods question

ashish kulkarni
Ranch Hand

Joined: Aug 15, 2002
Posts: 130
Hi,
I have a following class with 2 static methods, should
i make the methods synchronized??
I would not make then synchronized, if those where
independent,
but i am not sure since one method is calling other to get some data
I will call this method from any class
String a = MyClass.getOtherThing("123");
or
String b = MyClass.getSomeThing("567");
(this is just a example code)
public class MyClass
{
public static String getSomeThing(String abc)
{
// some logic
return "1";
}
public static String getOtherThing(String abc)
{
// calling method getSomeThing here
String s = getSomeThing(abc);
// do some logic and return result
return "2";
}
}


A$HI$H
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2861
    
  11

Synchronization is important when two things are true:
1. The methods may be called from mulitple threads at the same time.
2. The logic of the method changes the internal state of the object (or class in your case) in such a way that the state could become inconsistent unless the method is allowed to complete without interruption.
That means we don't have enough information to decide if you should synchronize or not. In general, "get" methods don't need to be synchronized, but that's not always true. You have to examine the logic, and ask yourself, "If the method were interrupted here and another method begun, would it lead to inconsistent results?" Repeat that question for every statement in the method. Eliminating race conditions is one of the hardest jobs of programming.
Wirianto Djunaidi
Ranch Hand

Joined: Mar 20, 2001
Posts: 210

The quick answer will be:
If your static method DOES NOT make any changes on any static variable than you don't have to synch them.
ashish kulkarni
Ranch Hand

Joined: Aug 15, 2002
Posts: 130
Hi,
I will be using this static methods from servlet so it is quite likely that they will be accessed at a same time by multiple instances of a servlet,
But in this case i dont change the value of any static variable in this class, also it does not change the state of the class with static method,
but most of the time what i do in those methods is date formating,
like i send in date and get the string in display format etc
So do i need to synchronized them,
i will not synchronize if those are stand alone methods like they work on there own and dont call any other method, but in this case i am not sure as one method is calling other
Ashish
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: using static methods question