I'm designing a custom logging framework for our application.
I'm reading Patterns For Logging Diagnostic Messages, which is being used in http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html
On page 3 it says:
Because it is a Singleton, it easily preserves the order of the messages.
I think, for example, given Singleton class S, if a class B is trying to acquire the instance of S while a class A already got the instance S, then B cannot acquire the instance of S since A already got the instance of S.
That's why the order of message is preserved based on my understanding.
Is my understanding correct?
How the class B knows that class A is done with the class S and no longer needs it so that B can acquire S?
if my understanding is correct and if Singleton class S has some methods: test1() and test2() as you see below.
Are test1() and test2() are thread-safe?
These methods will be called outside of class S, something like
S.getInstance().test1("message")
in class A or class B for example.
Which means when class A and class B are trying to write some data in a log file by calling test1(), this data will be written in the order of acquiring the instance of S?
If not, to make methods thread-safe in a Singleton class S, should I also use synchronized
keyword on methods test1() and test2() or lock
for these methods?
public class S { // singleton class S
private static S instance;
private S(){}
public static S getInstance(){
if(instance == null){
instance = new S();
}
return instance;
}
public static void test1(String log) {
// writing some data to a log file
}
public static void test2(String log) {
// writing some data to a log file
}
}