⌘K
Flycodx

Singleton Pattern: Thread-Safe Implementation

Singleton Pattern: Thread-Safe Implementation

EasyLLD0% accepted

Implement the Singleton design pattern in Java with thread safety. Show naive implementation, its problems in multi-threaded environment, and fix it using double-checked locking with volatile keyword.

Approach

Implement thread-safe Singleton using double-checked locking with volatile.

Input

Thread A and B both call getInstance() first time

Output

Double-checked locking: both enter first null check; one gets lock, creates instance; other sees non-null in second check

Scenarios & Expected Answers

Sign in to continue

Create a free account to view answers and mark progress.

  • Free forever — no credit card
  • Theory Q&A with detailed answers
  • Points, streaks & leaderboards
Auto Save On