0

I have Kafka client with the following code,

private AdminClient getKafkaClient() {
        final Map<String, Object> configs = new ConcurrentHashMap<>();
        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "server-ip");
        return AdminClient.create(configs);
    }

This method invoked by multiple thread, and creates many admin client. So i wanted to keep in one instance and make use of it.

I've read an article for Singleton using Holder class with the below url,

Regarding static holder singleton pattern

Looks good to me, when i tried to implement issue setting config and can't create instance. Can any one suggest me best idea in my problem?

Thank you!

parrotjack
  • 432
  • 1
  • 6
  • 18

1 Answers1

1

The following looks good?? I made it to work.

public class KafkaAdminManager {

    private ConnectionConfig connectionConfig;
    private static final Map<String, Object> configs =  new HashMap<>();

    public KafkaAdminManager(ConnectionConfig connectionConfig) {
        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, connectionConfig.getBootstrapServers());
        this.connectionConfig = connectionConfig;
    }

    private static class InstanceHolder {
        public static AdminClient instance = AdminClient.create(configs);
    }

    private KafkaAdminManager(){}

    public static AdminClient getInstance() {
        return InstanceHolder.instance;
    }

}
parrotjack
  • 432
  • 1
  • 6
  • 18