mike_shysh
12/02/2019, 1:57 PMobject DBProvider {
@Volatile private var dbSession: Session? = null
fun getDBSession(): Session = dbSession ?: synchronized(this) {
dbSession ?: when (dbType) {
DBTypes.MYSQL.type -> MySqlSession(host = dbHost, port = dbPort).getSession()
DBTypes.ORACLE.type -> OracleSession(host = dbHost, port = dbPort).getSession()
else -> throw Exception("Unsupported DB type - $dbType.")
}.also { dbSession = it }
}
...diesieben07
12/02/2019, 1:58 PMval dbSession by lazy { /* create session here */ } , which is thread-safe by default.mike_shysh
12/02/2019, 1:58 PMmike_shysh
12/02/2019, 1:59 PMprivate lateinit var dbSession: Sessiondiesieben07
12/02/2019, 1:59 PMdiesieben07
12/02/2019, 1:59 PMlazy has synchronization built-inmike_shysh
12/02/2019, 1:59 PMmike_shysh
12/02/2019, 2:02 PMdbSession be a static variable, or it does not matter?diesieben07
12/02/2019, 2:02 PMmike_shysh
12/02/2019, 2:03 PMmike_shysh
12/02/2019, 2:03 PMobject DBProvider its a singleton classdiesieben07
12/02/2019, 2:03 PMobject, there will only be one instance of that object and thus only one value for each of it's propertiesmike_shysh
12/02/2019, 2:03 PMmike_shysh
12/02/2019, 2:04 PMmike_shysh
12/02/2019, 2:05 PMobject DBProvider and at this very time another thread tries to obtain dbSessiondiesieben07
12/02/2019, 2:06 PMlazy has synchronization built in. It guarantees only one value will ever be createddiesieben07
12/02/2019, 2:06 PMmike_shysh
12/02/2019, 2:07 PMdbSessionmike_shysh
12/02/2019, 2:07 PMdiesieben07
12/02/2019, 2:07 PMby lazy { }mike_shysh
12/02/2019, 2:08 PMby lazy { } init
fun getDBSession(): Session {
dbSession = when (dbType) {
DBTypes.MYSQL.type -> MySqlSession(host = dbHost, port = dbPort).getSession()
DBTypes.ORACLE.type -> OracleSession(host = dbHost, port = dbPort).getSession()
else -> throw Exception("Unsupported DB type - $dbType.")
}
}
return dbSession
}diesieben07
12/02/2019, 2:09 PMmike_shysh
12/02/2019, 2:09 PMmike_shysh
12/02/2019, 2:09 PM