Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update RightLazySingleton.java #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,17 @@ public class RightLazySingleton {
private RightLazySingleton() {
}

public static synchronized RightLazySingleton getInstance() {
public static RightLazySingleton getInstance() {
if (instance == null) {
instance = new RightLazySingleton();
// Only synchronize once (i.e. we don't want to context switch every time getInstance is called!)
synchronized(RightLazySingleton.class) {
// Need the 2nd null check in case 1 or more threads were waiting for the lock, while
// the first thread assigned the instance. So, if 1 or more threads got past the first
// null check, they will not get past the 2nd when the first thread releases the lock.
if (instance == null) {
instance = new RightLazySingleton();
}
}
}
return instance;
}
Expand Down