The Artima Developer Community
Sponsored Link

Legacy Design Forum
Designing with Static Members



This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Singleton lazy initialization

Posted by Oleg on November 29, 2001 at 9:47 PM

If you use lazy initialization - initializing a Singleton
when is's requested for the first time, getInstance() must
be synchronized, otherwise, it is possible that if two
clients call getInstance() at the same moment, when they
check if it's null they both realize that it is null, and two
instances are created.

public static final Stack getInstance()

> You can do something like this:

> public class Stack
> {
> private static Stack mInstance = null;
> private Stack()
> {
> }

> public static final Stack getInstance()
> {
> if (mInstance == null)
> mInstance = new Stack();
> return mInstance;
> }
> }

> Basically, you always retrieve the singleton instance of Stack by going like this in your code:

> Stack theStack = Stack.getInstance();

> You use a static method, and the constructor is private so that other classes cannot instantiate it. The singleton instance is stored as a static reference.

> Hope this helps. I realize it's being answered several years after the question was asked.


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us