Skip to content

Commit 85ebc5d

Browse files
authored
Cache the result of JsonProvider.provider() (#485) (#486)
1 parent 2c73223 commit 85ebc5d

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

java-client/src/main/java/co/elastic/clients/json/JsonpUtils.java

+14-2
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,24 @@
4242

4343
public class JsonpUtils {
4444

45+
private static JsonProvider systemJsonProvider = null;
46+
4547
/**
4648
* Get a <code>JsonProvider</code> instance. This method first calls the standard `JsonProvider.provider()` that is based on
47-
* the current thread's context classloader, and in case of failure tries to find a provider in other classloaders.
49+
* the current thread's context classloader, and in case of failure tries to find a provider in other classloaders. The
50+
* value is cached for subsequent calls.
4851
*/
49-
@AllowForbiddenApis("Implementation of the JsonProvider lookup")
5052
public static JsonProvider provider() {
53+
JsonProvider result = systemJsonProvider;
54+
if (result == null) {
55+
result = findProvider();
56+
systemJsonProvider = result;
57+
}
58+
return result;
59+
}
60+
61+
@AllowForbiddenApis("Implementation of the JsonProvider lookup")
62+
static JsonProvider findProvider() {
5163
RuntimeException exception;
5264
try {
5365
return JsonProvider.provider();

java-client/src/test/java/co/elastic/clients/json/JsonpUtilsTest.java

+10
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,16 @@ public Enumeration<URL> getResources(String name) {
6969
}
7070
}
7171

72+
@Test
73+
@AllowForbiddenApis("Testing JsonpUtil.provider()")
74+
public void testProviderCache() {
75+
// A new provider at each call
76+
assertNotSame(JsonpUtils.findProvider(), JsonpUtils.findProvider());
77+
78+
// Result is cached
79+
assertSame(JsonpUtils.provider(), JsonpUtils.provider());
80+
}
81+
7282
@Test
7383
public void testObjectToString() {
7484
// Test that we call toString() on application classes.

0 commit comments

Comments
 (0)