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 PMprivate lateinit var dbSession: Session
diesieben07
12/02/2019, 1:59 PMlazy
has synchronization built-inmike_shysh
12/02/2019, 1:59 PMdbSession
be a static variable, or it does not matter?diesieben07
12/02/2019, 2:02 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 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 createdmike_shysh
12/02/2019, 2:07 PMdbSession
diesieben07
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 PM