simtse
03/24/2020, 7:27 PM@javax.inject.Singleton
class SpecificWork @Inject constructor() {
private var cruncher: Cruncher? = null
@GuardedBy("this")
init {
initCruncher()
}
@Synchronized
private initCruncher() {
// io work initialization
cruncher = try {
IOCruncher.init()
} catch (e: IOException) {
null
}
}
fun doWork(): Result? {
if (cruncher == null) {
return null
}
// do work
return Result("done")
}
}
This SpecificWorker
is provided via Dagger for dependency injection, but there could be many threads calling into it at the same time. I’m wondering
• Is there a case where the doWork()
started executing before the initCruncher()
was able to assign the cruncher
? Making the cuncher
null and failing early?trevjones
03/24/2020, 7:42 PMCruncher
on the graph as a @Singleton
and let dagger's built in double check locking handle it for you?
@Singleton
class SpecWork @Inject constructor(
private val cruncher: Cruncher
) {
fun doWork(): Result {
return Result("done")
}
}
trevjones
03/24/2020, 7:44 PMIOCruncher.init()
to fail. maybe model it as Optional<Cruncher>
?simtse
03/24/2020, 7:59 PMCruncher
in the graph as well. I’d probably make it more private in the graph so only my SpecWork
has access to it. I don’t want to expose the Cruncher
outside.trevjones
03/24/2020, 8:06 PM@Singleton
class SpecWork @Inject constructor() {
private val cruncher: Cruncher by lazy {
runCatching { IOCruncher.init() }.getOrNull()
}
fun doWork(): Result? {
return cruncher?.run { ... }
}
}