Updating geoip2 DatabaseReader in multithreaded environment

152 views Asked by At

I am using a DatabaseReader object from maxmind geoip2 API. val reader = new Builder(new FileInputStream(filePath)).build. This object is already thread safe and is shared between several reader threads. It stores the relevant information using an AtomicReference and implements the Closeable interface to release the data.

this.bufferHolderReference = new AtomicReference<>(bufferHolder);

I am periodically downloading a new database file and want to update the reader object to the new one. What would be the proper way of recreating this object so that the reader threads have no failures (they always get a correct object) and there is no memory leak. I tried wrapping this reader object in an AtomicReference too but I am having memory leaks for some reason.

def createReader: DatabaseReader = {
  ...
  new Builder(new FileInputStream(filePath)).build
}

val geoIpDatabase: AtomicReference[DatabaseReader] = new AtomicReference(createReader) //initialisation

//called periodically
def updateDb(): Unit = {
  val oldGeoDb = geoIpDatabase.get()
  geoIpDatabase.compareAndSet(oldGeoDb, createReader)
  oldGeoDb.close()
}
0

There are 0 answers