teacher
Sign in

Singleton

Guarantee one instance of a class, build it safely under threads, and know why it is often the wrong tool.

25 min5 interactive

The problem it solves

Some objects should exist once per program: a configuration holder, a connection pool, a logger.

A Singleton is a class that:

  • Allows only one instance (the constructor is private).
  • Gives everyone a way to reach it (a static getInstance()).

"Thread-safe" means it still creates exactly one instance when many threads call getInstance() at the same moment.

1 of 7