Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Singleton pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Lazy initialization === A singleton implementation may use [[lazy initialization]] in which the instance is created when the static method is first invoked. In [[Multithreading (software)|multithreaded]] programs, this can cause [[Race condition|race conditions]] that result in the creation of multiple instances. The following [[Java_version_history#Java_5|Java 5+]] example<ref>{{Cite book|author=Eric Freeman, Elisabeth Freeman, Kathy Sierra, and Bert Bates|title=Head First Design Patterns|publisher=O'Reilly Media, Inc|date=October 2004|edition=First|chapter=5: One of a Kind Objects: The Singleton Pattern|page=182|isbn=978-0-596-00712-6|chapter-url=https://books.google.com/books?id=GGpXN9SMELMC&pg=PA182}}</ref> is a [[Thread safety|thread-safe]] implementation, using lazy initialization with [[double-checked locking]]. <syntaxhighlight lang="java"> public class Singleton { private static volatile Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)