Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit3033e4c

Browse files
committed
Improve lazy loaded Singleton example
1 parente68beb4 commit3033e4c

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

‎singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,13 @@
2727
* <p>Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization
2828
* mechanism.</p>
2929
*
30-
* <p>Note: if created by reflection then a singleton will not be created but multiple options
31-
* in the same classloader</p>
3230
*/
3331
publicfinalclassThreadSafeLazyLoadedIvoryTower {
3432

35-
privatestaticThreadSafeLazyLoadedIvoryTowerinstance;
33+
privatestaticvolatileThreadSafeLazyLoadedIvoryTowerinstance;
3634

3735
privateThreadSafeLazyLoadedIvoryTower() {
38-
//protect against instantiation via reflection
36+
//Protect against instantiation via reflection
3937
if (instance ==null) {
4038
instance =this;
4139
}else {
@@ -44,13 +42,16 @@ private ThreadSafeLazyLoadedIvoryTower() {
4442
}
4543

4644
/**
47-
* The instancegetscreatedonly when it is called for first time. Lazy-loading
45+
* The instancedoesn't getcreateduntil the method is called forthefirst time
4846
*/
4947
publicstaticsynchronizedThreadSafeLazyLoadedIvoryTowergetInstance() {
5048
if (instance ==null) {
51-
instance =newThreadSafeLazyLoadedIvoryTower();
49+
synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
50+
if (instance ==null) {
51+
instance =newThreadSafeLazyLoadedIvoryTower();
52+
}
53+
}
5254
}
53-
5455
returninstance;
5556
}
5657
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp