Skip to content

Commit

Permalink
Make ConverterManager.getInstance() init thread-safe. (#776)
Browse files Browse the repository at this point in the history
  • Loading branch information
cpovirk authored Apr 5, 2024
1 parent 290a451 commit 34197d2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 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
7 changes: 5 additions & 2 deletions src/test/java/org/joda/time/convert/TestConverterManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,12 @@ public void testSingleton() throws Exception {
Constructor con = cls.getDeclaredConstructor((Class[]) null);
assertEquals(1, cls.getDeclaredConstructors().length);
assertEquals(true, Modifier.isProtected(con.getModifiers()));

Class holderCls = Class.forName(cls.getName() + "$LazyConverterManagerHolder");
assertEquals(true, Modifier.isPrivate(holderCls.getModifiers()));

Field fld = cls.getDeclaredField("INSTANCE");
assertEquals(true, Modifier.isPrivate(fld.getModifiers()));
Field fld = holderCls.getDeclaredField("INSTANCE");
assertEquals(true, Modifier.isFinal(fld.getModifiers()));
}

//-----------------------------------------------------------------------
Expand Down

0 comments on commit 34197d2

Please sign in to comment.