Skip to content

Commit

Permalink
Initialize the default StatusLogger instance lazy
Browse files Browse the repository at this point in the history
  • Loading branch information
vy committed Jan 29, 2024
1 parent c4c941e commit 3684a2e
Showing 1 changed file with 16 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,20 @@ private static Properties readPropertiesFile() {
}
}

private static volatile StatusLogger INSTANCE = new StatusLogger();
/**
* Wrapper for the default instance for lazy initialization.
* <p>
* The initialization will be performed when the JVM initializes the class.
* Since {@code InstanceHolder} has no other fields or methods, class initialization occurs when the {@code INSTANCE} field is first referenced.
* </p>
*
* @see <a href="https://www.infoworld.com/article/2074979/double-checked-locking--clever--but-broken.html?page=2">Double-checked locking: Clever, but broken</a>
*/
private static final class InstanceHolder {

private static volatile StatusLogger INSTANCE = new StatusLogger();

This comment has been minimized.

Copy link
@andrei-ivanov

andrei-ivanov Jan 29, 2024

is volatile needed in this case?

This comment has been minimized.

Copy link
@vy

vy Jan 29, 2024

Author Member

Given setLogger() and getLogger() can be accessed concurrently, to comply with JMM, and if my JCiP memory serves right, yes? Why do you think it is not needed?

This comment has been minimized.

Copy link
@andrei-ivanov

andrei-ivanov Jan 29, 2024

that's how I remembered it, that the holder pattern means volatile is not needed... reading https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom seems to confirm it

This comment has been minimized.

Copy link
@vy

vy Jan 29, 2024

Author Member

@andrei-ivanov, holder-idiom helps with the lazy-one-time-initialization, but it doesn't help with the memory ordering in case of a mutation. In the link you shared, INSTANCE is final. Here, it is not, and hence the volatile guard.


}

private final Config config;

Expand Down Expand Up @@ -351,7 +364,7 @@ public StatusLogger(
* @return the singleton instance
*/
public static StatusLogger getLogger() {
return INSTANCE;
return InstanceHolder.INSTANCE;
}

/**
Expand All @@ -363,7 +376,7 @@ public static StatusLogger getLogger() {
* @since 2.23.0
*/
public static void setLogger(final StatusLogger logger) {
INSTANCE = requireNonNull(logger, "logger");
InstanceHolder.INSTANCE = requireNonNull(logger, "logger");
}

/**
Expand Down

0 comments on commit 3684a2e

Please sign in to comment.