Let say I have the following method, is the method thread safe?
public static void forwardProcessingPerStudy(String str)
{
someNonStaticMethodProcessingOnObj(str);
}
I.e: Could two separate threads run the above method at the same time passing different instance of str ( say two completely different string objects ) and conflict with each other?
For the method to be safe for thread use do I have to make it a synchronized method?
Yes, two different threads could both run that method at the same time, with either the same string reference or a different one.
As to whether you need to synchronize, that entirely depends on what someNonStaticMethodProcessingOnObj does. The name implies it's calling a non-static method, but given that you don't specify an instance on which to call it, that seems unlikely.
If the body of the method (and any methods that are called) doesn't do anything with any shared state, you don't need to worry. If it does, you need to think more carefully.
Yes.
No.
But the answers with method someNonStaticMethodProcessingOnObj could be different.
The method shown is threadsafe, since it doesn't access any stateful information on any object.
That being said, we have no idea if someNonStaticMethdoProcessingOnObj() is or not, not to mention that the name implies it is non static but it isn't run against any instance.
Here's an answer to a similar question where I added some examples that might make this clear for you:
difference between synchronizing a static method and a non static method
The thing is that adding synchronized to the outer method might not help, as that synchronizes on the associated Class object. The inner method might need to be synchronized on something else. So some care is needed.
Related
If method have return type and it is access by two or more thread then it is required to use synchronized block or keyword with this method?
No. If that method does changes any of the field of the object that its operating upon (i.e. changing the state of object) and same object is shared amongst two thread then you might need it.
You may need to use synchronized when you are reading fields which can be changed in another thread, or writing fields which might be read in another thread. There is no specific rule of when you must, or must not use synchronized or the language would be able to do this for you. It is up to you to decide based on you use case.
It is not required. For example, if your class does not offer methods which modify instances of this class (then the class is said to be immutable) you don't need to synchronize.
However, as soon as at least one thread can write to some member variable, and there exist other threads which can read from or write to this variable at the same time, you need to synchronize the access to this variable, either by using the synchronized keyword or by manipulating locks explicitly. In some cases, you might also use atomic operation (AtomicInteger, for example).
Assuming all method calls here are static, like this:
public class Util {
public static void method1() {
}
}
Accessing in a static way:
Util.method1();
Util.method2();
Util.method3();
accessing in a non static way
Util util = new Util();
util.method1();
util.method2();
util.method3();
Is there any performance difference for either way? I know the first way of doing it here is accessing it properly. But the second way only instantiates the util object once as opposed to three times. I can't find anything pointing to anything other than to be accessing these methods properly. From what I can tell there is no functional difference, but a logical difference. Looking for sort of a cost vs. benefit of either way if anyone knows.
Is there any performance difference for either way?
Yes - the second is marginally slower, due to a pointless instance being constructed.
I know the first way of doing it here is accessing it properly. But the second way only instantiates the util object once as opposed to three times.
No, the second way creates one instance of Util whereas the first way doesn't create any instances.
The first way is significantly better, because it makes it clear that it is a static method. Consider this code:
Thread t = new Thread(someRunnable);
t.start();
t.sleep(1000);
What does it look like that last call does? Surely it makes the new thread sleep, right? No... it just calls Thread.sleep(), which only ever makes the current thread sleep.
When you mangle a static method call to act "through" a reference, the value of the reference is completely ignored - it can even be null:
Util util = null;
util.method1(); // This will still work...
There's no difference for the code you show, since all those methods are static. (The compiler will issue a warning for the second group, however.) I think there's a small performance benefit to static methods. The underlying byte code for static access, invokeSpecial I think, should be faster than invokeVirtual, which has to do some type decoding.
But it's not enough to worry about. Use whichever type of method (static vs. instance) is right for your design. Don't try to optimize the method calls like that.
I have a function in a class, which just masks the input card number. I have made it synchronized because, i do not want more than one thread calling my maskcard function simultaneously. My question is, should i make this function static to be more efficient and clean? Now, where ever i am calling my maskcard function, i am calling on an instance.
public class CardMasker {
public synchronized String maskCardNumber(String cardNumber)
{
..
..
}
}
A better solution would be to make sure that you have only one CardMasker instance and use non-static synchronized maskCardNumber.
I you keep the method instance specific i.e. the way you have implemented it currently :
public synchronized String maskCardNumber(String cardNumber)
Here all the threads working on same instance will access the method in synchronized fashion.
If you want to make it static synchronized, here are the points to be considered:
Does it perform operation which needs to be accessed in synchronized fashion irrespective of any instance of this class. If yes, then there is no point keeping it instance specific, because threads using different instances of this class will still be able to call the method simultaneously.
My question is, should i make this function static to be more efficient and clean?
No. It won't make it more efficient. The difference in speed (if there is any at all) will be negligible.
Furthermore, if you then make the method synchronized, you are creating a concurrency bottleneck. This doesn't need to happen in the non-static case; for example if you resist the temptation to "save space" (or something) by using a singleton. Indeed, if each thread has its own thread-confined instance of the class that implements this helper method, then the method probably doesn't need to be synchronized at all.
Also, it is a matter or opinion, but static methods are not more "clean" than instance methods.
Do methods that only use local variables inside suffer any threading issues ?. Somewhere it was mentioned that the method with local variables are copied to each thread stack frame to work with and do not need to synchronized for multithreaded implementation unless it uses class level or static references/variables ?
If your method only operates on parameters and locally-defined (as opposed to class member) variables then there are zero synchronization problems to worry about.
But...
This means any mutable reference types you use must live and die only within the scope of your method. (Immutable reference types aren't a problem here.) For example this is no problem:
int doSomething(int myParameter)
{
MyObject working_set = new MyObject();
interim = working_set.doSomethingElse(myParameter);
return working_set.doSomethingElseAgain(interim);
}
A MyObject instance is created within your method, does all of its work in your method and is coughing up blood, waiting to be culled by the GC when you exit your method.
This, on the other hand, can be a problem:
int doSomething(int myParameter)
{
MyObject working_set = new MyObject();
interim = working_set.doSomethingElse(myParameter);
another_interim = doSomethingSneaky(working_set);
return working_set.doSomethingElseAgain(another_interim);
}
Unless you know for sure what's going on in doSomethingSneaky(), you may have a need for synchronization somewhere. Specifically you may have to do synchronization on the operations on working_set because doSomethingSneaky() could possibly store the reference to your local working_set object and pass that off to another thread while you're still doing stuff in your method or in the working_set's methods. Here you'll have to be more defensive.
If, of course, you're only working with primitive types, even calling out to other methods, passing those values along, won't be a problem.
Does methods that only use local variables inside, do not suffer any threading issues ?
True in a very simplistic sense, but lets be clear - I think this is only true if:
such a method uses only local variables that are primitives or references to mutable instances that cannot otherwise be accessed outside the method by any other means.
such a method invokes only methods that are thread-safe.
Some ways these rules could be violated:
A local variable could be initialized to point to an object that is also accessible outside the method. For example, a local variable could point to a singleton (Foo bar = Foo.getSingleton()).
A local instance held by a local variable could "leak" if the instance is passed as a argument to an external method that keeps a reference to the instance.
A class with no instance variables and with only a single method with no local variables could still call the static method of another class that is not thread-safe.
The question is very generic, so please do not expect any specificity from my answer.
1_ We need to more careful with static methods than say instance methods.
2_ #Justmycorrectopinion is about right, but some of the terms he described needs to be more elaborated to be perfect. ( Even if the static method, only works on local variable, there is still possibility of race condition.)
3_ For me there are simple rules that have helped me analyze thread safety.
Understand if each components encapsulated within it is shareable or not. So the simplest solution is to reduce the scope of all variable and only increase scope if absolutely necessary and if component perform mutation on a object, its usually not thread safe.
4_ Use tooling support to perform static code analysis on thread safety. (Idea has checkthread plugin).
5_ Never use static method to perform object mutation. If calling static variable causes object mutation, then the developer is just circumventing OOPS.
6_ Always document thread safety. Remember some method may not need to be synchronized when you develop, but can be made not thread safe very easily.
7_ Last but probably my most important point, make sure most of your objects are immutable. In my experience, most of the time, I never had to make many of my objects mutable. (In rare cases when object state needs to be changed, defensive copying / New Object Creation is almost always better. )
You do not need to worry about local variables. Instance variables however are something to care about.
I've problem understanding the following piece of code:-
public class SoCalledSigleton{
private final static boolean allDataLoaded = SoCalledSigleton();
private SoCalledSigleton(){
loadDataFromDB();
loadDataFromFile();
loadDataAgainFromDB();
}
}
Is this piece of code thread safe? If not then Why?
This will create an error in Java.
private final static boolean allDataLoaded = SoCalledSigleton();
You're assigning an object to a boolean variable.
You forgot to add new to instantiate the variable.
But if your code is like this
public class SoCalledSigleton{
private final static SoCalledSigleton allDataLoaded = new SoCalledSigleton();
private SoCalledSigleton(){
loadDataFromDB();
loadDataFromFile();
loadDataAgainFromDB();
}
}
It is thread-safe as static initialization and static attributes are thread-safe. They are initialized only once and exists throughout the whole life-cycle of the system.
The code is unusable in its current form, so any notions of thread safety are irrelevent.
What public interface would users use to get an instance of the singleton?
(I assume that allDataLoaded is meant to be a SoCalledSigleton and boolean is just a typo :-)
If the class has no other constructors, or the loadData* methods don't do funny business (such as publishing this), its initialization is thread safe, because the initialization of final static data members is guarded by the JVM. Such members are initialized by the class loader when the class is first loaded. During this, there is a lock on the class so the initialization process is thread safe even if multiple threads try to access the class in parallel. So the constructor of the class is guaranteed to be called only once (per classloader - thanks Visage for the clarification :-).
Note that since you don't show us the rest of the class (I suppose it should have at least a static getInstance method, and probably further nonstatic members), we can't say anything about whether the whole implementation of the class is thread safe or not.
From what we can see, there are no specific issues - it's guaranteed that the constructor will only ever by called once (so by definition can't be run multithreaded), which I presume is what you were concerned about.
However, there are still possible areas for problems. Firstly, if the loadData... methods are public, then they can be called by anyone at any time, and quite possibly could lead to concurrency errors.
Additionally, these methods are presumably modifying some kind of collection somewhere. If these collections are publically accessible before the constructor returns, then you can quite easily run into concurrency issues again. This could be an issue with anything exception updating instance-specific fields (static fields may or may not exhibit this problem depending where they are defined in the file).
Depending on the way the class is used, simply writing all of the data single-threaded may not be good enough. Collection classes are not necessarily safe for multi-threaded access even if read-only, so you'll need to ensure you're using the thread-safe data structures if multiple threads might access your singleton.
There are possibly other issues too. Thread-safety isn't a simple check-list; you need to think about what bits of code/data might be accessed concurrently, and ensure that appropriate action is taken (declaring methods synchronized, using concurrent collections, etc.). Thread-safety also isn't a binary thing (i.e. there's no such thing as "thread safe" per se); it depends how many threads will be accessing the class at once, what combinations of methods are thread-safe, whether sequences of operations will continue to function as one would expect (you can make a class "thread safe" in that is doesn't crash, but certain return values are undefined if pre-empted), what monitors threads need to hold to guarantee certain invariants etc.
I guess what I'm trying to say is that you need to think about and understand how the class is used. Showing people a snapshot of half a file (which doesn't even compile), and asking them to give a yes/no answer, is not going to be beneficial. At best they'll point out some of the issues for you if there are any; at worst you'll get a false sense of confidence.
Yeah, it's thread safe. The "method" is the constructor, and it will be called when the class is loaded, i.e. exactly once.
But looking at the stuff being done, I think it's probably a lousy idea to call it from the class loader. Essentially, you'll end up doing your DB connection and stuff at the point in time when something in your code touches the SoCalledSingleton. Chances are, this will not be inside some well-defined sequence of events where, if there's an error you have catch blocks to take you to some helpful GUI message handling or whatever.
The "cleaner" way is to use a synchronized static getInstance() method, which will construct your class and call its code exactly when getInstance() is called the first time.
EDIT: As The Elite Gentleman pointed out, there's a syntax error in there. You need to say
private final static SoCalledSingleton allDataLoaded = new SoCalledSigleton();