0

I have a singleton class. one of his methods is:

public static void printMessage(boolean print, String text) {
    if (print) {
        System.out.print(text);
    }
}

I have a multithreaded application, and more than one thread are using this method. I'm not sure, but do I need to add mutex to the implementation of printMessage ? I think that I dont need to, because I'm not using any class member. Am I right ?

user3668129
  • 4,318
  • 6
  • 45
  • 87
  • There really isn't much info in your question.From the look of this one method, I don't see a reason why you would need a "mutex" around anything – Alex Jun 03 '14 at 04:27
  • @user3668129 you are right, no need to add locks here. But you should document your method as in future some one can put class member inside this. – Vipin Jun 03 '14 at 04:36
  • As per open JDK source code println() method is thread safe. while print() method is not. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/PrintStream.java#PrintStream.println%28java.lang.String%29 – Rakesh Soni Jun 03 '14 at 05:26

2 Answers2

0

It's a static method which only uses parameters. One of the parameters is primitive and the other is immutable. I don't see a reason to synchronizing the method.

TyeH
  • 1
0

In this specific case, you are not accessing any shared storage such as member variables, static fields, etc. However, you also need to look at any functions you call. Are they thread-safe? In your case, is System.out.print thread-safe? If it is not, then two calls such as:

//Thread 1
printMessage(true, "abc");

// Thread 2
printMessage(true, "def");

might print:

adebcf

because of interleaving.

Now, the Javadoc for print makes no mention of thread safety. Hence, assume that it is not thread-safe.

It is up to you to decide whether text interleaving is a problem for your use case. If so, then take proper precautions to prevent interleaving of print output.

metacubed
  • 7,031
  • 6
  • 36
  • 65