我正在尝试了解Kotlin上的协程,并且对此主题有一些疑问。
这些作业是通过ScheduledService中的foreach循环创建的,该循环可检索任务,并且每个任务都以此方式运行协程作业
fun executeUploadJob(transporter: Transporter, taskId: Long) {
GlobalScope.launch {
exportTaskRepository.findById(taskId).ifPresent { task ->
task.status = TaskStatus.IN_PROGRESS
exportTaskRepository.save(task)
}
transporter.executeSingleFilesTransportCycle()
}.invokeOnCompletion {
when (it) {
null -> {
exportTaskRepository.findById(taskId).ifPresent { task ->
task.status = TaskStatus.UPLOADED
task.lastUpdated = Timestamp(System.currentTimeMillis())
exportTaskRepository.save(task)
}
}
//means that job was cancelled from outside and it should not be counted as error
is CancellationException -> {
logger.warn("Job was cancelled..[Task Id - $taskId]", it)
exportTaskRepository.findById(taskId).ifPresent { task ->
task.lastUpdated = Timestamp(System.currentTimeMillis())
task.nextAttempt = Timestamp(System.currentTimeMillis() + THIRTY_MINUTES)
task.status = TaskStatus.WAITING
exportTaskRepository.save(task)
}
}
else -> {
logger.error("Error while uploading file [TaskId - $taskId]", it)
exportTaskRepository.findById(taskId).ifPresent { task ->
task.lastUpdated = Timestamp(System.currentTimeMillis())
task.nextAttempt = Timestamp(System.currentTimeMillis() + THIRTY_MINUTES)
task.status = TaskStatus.WAITING
exportTaskRepository.save(task)
}
}
}
}
}
我的问题是:1)如果引发任何异常,当前协程是否会在JVM中存在,或者它将消失并且不存在内存泄漏以及对Job的引用? 2)将作业引用保存到某个位置以定期跟踪其状态是否正确?