I have a class TestLogger that has a void method log(String s), which may be accessed by multiple threads. Here is my code
public class TestLogger {
private static final StringBuffer buffer = new StringBuffer();
public static void log(String s) {
buffer.append(s);
}
}
I am not sure here if I used the thread safe class StringBuffer, do I still need to put synchronized keyword on the method log(String) to ensure thread safety of the method? And how about this method
public static void log(String s, int type) {
if (type == 0)
buffer.append(s);
if (type == 1)
buffer.append("SOME HEADER " + s);
}
here type is not modified in the method log. Do I need to use synchronized keyword?
In Java, there are both synchronized keyword and thread safe classes that can provide thread safety. I am not sure when to use one and the other?