-1

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)
    {
        ..
        ..
    }

}
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
Anita
  • 185
  • 1
  • 6
  • 24

3 Answers3

1

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.
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
1

A better solution would be to make sure that you have only one CardMasker instance and use non-static synchronized maskCardNumber.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • If i just do it this way to have only one CarkMasker instance. Is it fine? Or should i synchronize my getInstance() method as well? public static CardMasker getInstance() { if (null == instance) { instance = new CardMasker(); } return instance; } – Anita Dec 23 '13 at 09:19
  • There are different approaches to make a thread-safe singleton, you can find examples in inet. But I suggest to consider a dependency injection framework like Spring or Guice – Evgeniy Dorofeev Dec 23 '13 at 09:39
1

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216