Skip to content

Commit

Permalink
[KIE-1662 10.0.x] Make KieServiceLoader cache thread-safe (#6178)
Browse files Browse the repository at this point in the history
* [KIE-1662 10.0.x] Make KieServiceLoader cache thread-safe

* wip

* wip
  • Loading branch information
mariofusco authored Dec 3, 2024
1 parent a4bbb75 commit 45d8ca1
Showing 1 changed file with 10 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,19 @@
*/
package org.kie.api.internal.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

import static org.kie.api.internal.utils.KieService.UNDEFINED;

public class KieServiceLoader {

static final KieServiceLoader INSTANCE = new KieServiceLoader();

private final Map<String, KieService> serviceCache = new HashMap<>();
private static final KieService DUMMY_SERIVCE = new KieService() {};

private final Map<String, KieService> serviceCache = new ConcurrentHashMap<>();

private KieServiceLoader() {}

Expand All @@ -38,11 +40,14 @@ <T extends KieService> T lookup(Class<T> serviceClass) {

<T extends KieService> T lookup(Class<T> serviceClass, String tag) {
String serviceKey = serviceClass.getName() + ":" + tag;
if (serviceCache.containsKey(serviceKey)) {
return (T) serviceCache.get(serviceKey);

T cachedService = (T) serviceCache.get(serviceKey);
if (cachedService != null) {
return cachedService == DUMMY_SERIVCE ? null : cachedService;
}

T loadedService = load(serviceClass, tag);
serviceCache.put(serviceKey, load(serviceClass, tag));
serviceCache.put(serviceKey, loadedService == null ? DUMMY_SERIVCE : loadedService);
return loadedService;
}

Expand Down

0 comments on commit 45d8ca1

Please sign in to comment.