I have read many stackoverflow questions on this but phrased differently and not answered what I was looking for. I don't expect any code solutions but a behavioral explanation of singleton object in multi-threaded environment. Answers with some links with explanation would be great.
Question 1: If there are multiple thread that needs to access singleton object(say configured as singleton bean in spring config), then is it that only one thread is able to get access and others are blocked till current holding thread releases it.
For me blocking here makes sense, because there is only one object and all threads cannot get same object at the same time.
So if I configure my DAO as singleton bean then if multiple users(threads) try to do reads and write through that DAO then it doesn't actually happen concurrently but sequentially ---> a performance issue in database intensive application.
On the other hand most of the DAOs are stateless(atleast in my case), so instead of configuring it as Singleton, I can instantiate it wherever I need and do the operations concurrently, but each object instantiation may take some time and memory. So it is a design decision.
In my case, since DAO has no state variable so memory would be negligible, so if my above theory is correct then I would go with 2nd option i.e. choosing concurrency over memory.
Question 2: For the question asked here
I think the best answer is below by S.Lott(I don't know how to point link directly to the answer so copying the answer):
Singletons solve one (and only one) problem.
Resource Contention.
If you have some resource that
(1) can only have a single instance, and
(2) you need to manage that single instance,
you need a singleton.
Here my question is if above answer is true--> That would be the reason for loggers implemented as singletons because you have one log file(single resource).
You don't want that due to time slicing if one thread has written part of some log into the file and then suspended and then thread-2 writes its part and then thread-1 again, thereby making log file gibberish.
I stroke above text because I think if one thread is logging then second thread cannot log at all(blocked) because of singleton config, there by avoiding making log file a gibberish.
Is my understanding right?