Thursday, November 5, 2009

Singleton in multi-threaded environment

Question: How would you write a singleton in a multi-threaded environment?

In a singleton, there are two race conditions; one where the instance is created and the other when we access instance data. The method which creates the singleton instance must be made thread safe. Here is an example: