2

I am working on some code where I create a HikariDataSource as a by lazy value. I did apply the mode LazyThreadSafetyMode.SYNCHRONIZED, so I am confused as to why the initialization is done twice when I spin up a new thread that reads that value

// in module database
val dataSource: HikariDataSource by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
    HikariDataSource(dataSourceConfig(databaseConfig))
}

fun initDatabase() {
  dataSource.connect().let { //do stuff}
}

// in main module
fun main() {
  initDatabase()
  thread {
    dataSource.connect().let { // initializes a new data source... }
  }
}

I would expect the HikariDataSource to be initialized once, but for some reason its called twice... I think the fact that I am exposing that variable to another gradle project might affect it, but not sure why..

1 Answer 1

3

Well, I think I just answered my own question...

The main module that access the dataSource object is a ktor server that was configured for hot reload.. As soon as I disabled the hotreload and tried again, the variable was not initialized twice.

I guess ktor is doing some stuff with the classloader for hot reload that causes this thing to happen.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a life-saver. Such a nasty issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.