Is the ProviderFactory singleton?

I’ve created a custom PolicyProvider, however, I’ve seen that it’s not singleton because the logs from the created method are logged with each interaction with Keycloak

public class DescendantGroupPolicyProviderFactory
        implements PolicyProviderFactory<DescendantGroupPolicyRepresentation> {
    private final DescendantGroupPolicyProvider provider = new DescendantGroupPolicyProvider();
    private static final Logger log = Logger.getLogger(DescendantGroupPolicyProviderFactory.class);

    public PolicyProvider create(AuthorizationProvider authorizationProvider) {
        log.infof("A %s is being created", DescendantGroupPolicyProvider.class.getSimpleName());
        return provider;

Should the PolicyProviderFactory be singleton?


I’ve been using UserStorageProviderFactory and it looks like it’s the same idea.
The factory is not a singleton, the factory is called for every Keycloak transaction, and it is up to you, according to your needs, to implement this object construction as a singleton or not.

As I can see from your code snippet, DescendantGroupPolicyProvider is a singleton, but DescendantGroupPolicyProviderFactory is not. It is a factory :slight_smile:

Long history short: I think the XXXXXProviderFactory implements the factory pattern to generate providers, and it’s up to you to generate each time a different one or use the singleton pattern to return always the same provider instance.

Hope that helps!

1 Like

A ProviderFactory class is not implemented as a singleton, as it is a Factory and thus should follow this pattern. But all ProviderFactory classes are only instantiated only once at container startup.

The create() method of a ProviderFactory class (instance) is called more often, but this doesn’t mean that it is every time another instance. Whether your ProviderFactory.create() returns a Provider singleton instance or a new instance on every call, is up to your implementation and depends a bit on what your actual provider implementation relies on and needs. So, if you need current information about the current state (e.g. KeycloakSession and realm, client, etc.), it might be better to create a new instance. If you just process data independent from state, a singleton might be enough.

1 Like