lundi 17 juin 2019

How to reinitialize a Singleton (KafkaProducer) during runtime?

I've a class which creates Kafka producers based on configs from a dynamic cahce. The configs were pretty much fixed, but now we are exploring the possibility of re-initializing the Kafka producer if the config has been changed at runtime. The cahce is basically a HashMap which is refreshed periodically from a DB.

What I've done now is to check the Cache to before I send the message and if the value is changed call the init() method which has a double check lock.

private volatile String config;
init(){
...
}

sendMessage(String message, String topic){
  if(config != Cahce.config())
  synchronized(){
    if(config != Cahce.config())
    init();
  }
}

I've tested this out in Dev environment it seems to work and unit testing was a pain(lot of mocks). I'm also currently modifying it so that the init() part is moved to a Factory.

I wanted to check if the implementation can be done any better ? Also I see a Sonar warning on this line:

private volatile String config;

This is what I've in mind so far, still not sure if I need an AbstractFactory: Kafka factory The application uses Spring.

Aucun commentaire:

Enregistrer un commentaire