This is probably the single most difficult question I know of with respect to Java programming. I've never met a single person who can answer it who hasn't already seen it before -- and I work with some scary-smart Java hackers.
So the problem is as follows. You have a singleton class (only one instance ever can exist), and you'd like to not initialize it until you actually need it (lazy initialization). Furthermore, it needs to be thread-safe, so that if multiple people try to grab it at the same time, you only allocate one instance. So you start out with:
That works great. However, you'd like to avoid the hit of the synchronization every time you call getInstance() -- it's a lot of overhead to pay each time.
Can you do this safely? If so, how? If not, why not?
So the problem is as follows. You have a singleton class (only one instance ever can exist), and you'd like to not initialize it until you actually need it (lazy initialization). Furthermore, it needs to be thread-safe, so that if multiple people try to grab it at the same time, you only allocate one instance. So you start out with:
code:<HR>Code:public class Foo { private static Foo instance = null; public static synchronized Foo getInstance() { if (instance == null) instance = new Foo(); return instance; } }
That works great. However, you'd like to avoid the hit of the synchronization every time you call getInstance() -- it's a lot of overhead to pay each time.
Can you do this safely? If so, how? If not, why not?