Skip to content

Commit

Permalink
Make ConverterManager.getInstance() init thread-safe.
Browse files Browse the repository at this point in the history
We encountered a TSAN error because 2 threads were racing to call
`ConverterManager.getInstance()`. My read is that the current code could
actually be unsafe, since one thread might see `INSTANCE` as non-null
before the other thread has initialized its fields.

Fortunately, this looks like a good case for [the
initialization-on-demand holder
idiom](https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#:~:text=initialization%20on%20demand%20holder%20idiom).

(There would be additional thread-safety concerns if anyone were to try
to _mutate_ the `ConverterManager` instance concurrently with usage. But
I'm not sure there's a solution to that short of spraying `synchronized`
around. That seems like probably overkill, given the possible
performance impact for what I'd hope is an uncommon use case.)
  • Loading branch information
cpovirk committed Mar 28, 2024
1 parent 290a451 commit f3f3f77
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/main/java/org/joda/time/convert/ConverterManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,14 @@
public final class ConverterManager {

/**
* Singleton instance, lazily loaded to avoid class loading.
* Holds the singleton instance, lazily loaded to avoid class loading.
*/
private static ConverterManager INSTANCE;
private static final class LazyConverterManagerHolder {
static final ConverterManager INSTANCE = new ConverterManager();
}

public static ConverterManager getInstance() {
if (INSTANCE == null) {
INSTANCE = new ConverterManager();
}
return INSTANCE;
return LazyConverterManagerHolder.INSTANCE;
}

private ConverterSet iInstantConverters;
Expand Down

0 comments on commit f3f3f77

Please sign in to comment.