Static method in multi threaded application - java

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.

Related

Is there a pthread_once equivalent in Java?

In C/C++ world, it is very easy make a routine executed just once by using pthread_once. In Java, I generally use static atomic variables to do the explicit check if the routine was run already. But that looks ugly and hence wondering if there is something like pthrea_once in Java.
Since you refer to “static atomic variables” you seem to talk about static resources which do not need special actions if you initialize them within the class initializer itself:
class Foo {
static ResourceType X = createResource();
}
Here, createResource() will be executed exactly once in a thread-safe manner on the first use of Foo, e.g. when Foo.X is accessed the first time. Threads accessing X while the class initialization is in progress are forced to wait, but subsequent access will be performed without any synchronization overhead. Typically, but not necessarily, the variable will be declared final as well.
If you have multiple resources whose creation should be deferred independently, the owner class might use inner classes, each of them holding one resource.
If your question is about an action which should be executed exactly once without returning a value, the static initialization can be used as well. You only have to add a member you can access to trigger the class initialization, e.g.:
class Foo {
static { performAction(); }
static void performActionOnce() {}
}
Here, calling Foo.performActionOnce() will cause performAction() to be executed the first time while all other subsequent invocations do nothing. You can also rely on that on returning from performActionOnce() the action within performAction() has been completed, even when there is contention on the first invocation.
This is different from any atomic variable approach as atomic variables do not provide a sufficient waiting capability for the case that the first invocation is contended. If you combine the atomic variable with a waiting queue, you end up what Lock (or any other AQS based concurrency tool) provides. For instance variables where the static initialization does not work, there is no simple workaround (besides thinking about whether initialization really has to be lazy).

Does accessing methods in a non static way affect/benefit performance?

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.

Is making a method synchronized when the method is only called in a synchronized block redundant? What happens on the OS level?

Let's say you have a method foo() that is only called in a synchronized block.
Is making the method
synchronized void foo() {..}
versus just
void foo() {..}
redundant or bad practice, or does it make the method's intent clearer? Does having the synchronized keyword on the method signature make the program slower? I'm wondering what the better practice is, or if I'm missing part of the big picture.
Thanks.
Usually, this means the foo() is not an atomic action itself, it probably does not preserve invariants, it is only part of the grander synchronization scheme.
Then it should not declare synchronized, otherwise reader might get the wrong idea; and it is a bit slower too.
Instead, you could
void foo()
{
assert Thread.holdsLock(this);
...
}
it serves 2 purposes
document that this method can only be invoked within an outer synchonized(this) block
check that requirement at runtime (I'll enable assersion for all non-production runs)
It's not redundant and in practice it's reasonably common to synchronise on locks you already hold.
APIs that have clearly defined boundaries between what's threadsafe and what's not are easier to work with, and the best boundary is probably at the class level. So, if the rest of the class is threadsafe and the foo() method will be threadsafe if synchronised then you may as well do it and make a note of it in your class doc. If synchronising foo() will give you an API with mixed threadsafe and non-threadsafe calls then that's going to lead to confusion later on.
Regarding performance I doubt it'll be an issue (uncontested locks should have minimal overhead). Get the code working and then see if you need to make it faster.
I imagine your foo() method is in a class A, and the caller code (which calls it inside a synchronized block) is in another class B.
My advice is not to make methods of A synchronized, because in single-threaded programs invocations will be systematically slower.
It is better to make the client classes (such as B) to carry out the synchronization job, by using synchronized blocks, as you pointed out.
In summary, my advice is to not declare the method synchronized, because it is more flexible: you can make thread-safe programs using your class with external synchronized blocks and also make fast single-threaded applications. You can also warn your users that your class A is not thread-safe.

Non-synchronized static methods & thread safety

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.

Threads and synchronisation

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();

Categories

Resources