fix: Task 12 완료 - ForeGroundService targetUrls 동기화 및 YoutubeDL Mutex 직렬화

- ForeGroundService.kt:
  * addToTargetYtubeUrl(): targetUrls 접근을 synchronized(targetUrls) 블록으로 보호
  * downloadVideo(): 비관리 CoroutineScope 대신 serviceScope.launch(Dispatchers.IO) 사용 및 downloadMutex.withLock 적용으로 YoutubeDL 동시 실행 경쟁 방지
  * currentProcessId, lastProGress에 @Volatile 적용 및 finally 블록에서 대기열 후속 작업 안전 트리거
  * launchAppleMusic(): CoroutineScope(Dispatchers.Main) -> serviceScope.launch(Dispatchers.Main) 전환
- TODO.md: 2-3 항목 완료 처리
- 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (3s)
This commit is contained in:
2026-11-16 11:38:58 +09:00
parent a0bc32cb95
commit 6b36757337
2 changed files with 20 additions and 14 deletions
+1 -1
View File
@@ -80,7 +80,7 @@
- `app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt:68, 106` — `pushLocation()` 호출마다 `Executors.newSingleThreadScheduledExecutor().schedule(...)`로 새 스레드 풀을 생성하고 `shutdown()`을 호출하지 않음. 또한 `130-131`행에서 `Companion.lastWeather.clear()` / `addAll()`을 백그라운드 스레드에서 동기화 없이 수정함.
- **작업**: 단일 공유 `CoroutineScope` + `delay(5000)`으로 대체하고 `lastWeather` 갱신 시 스레드 안전한 컬렉션 또는 `StateFlow` 사용.
- [ ] **2-3. `ForeGroundService` 공유 상태 및 `YoutubeDL` 동시 실행 제어**
- [x] **2-3. `ForeGroundService` 공유 상태 및 `YoutubeDL` 동시 실행 제어**
- `app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt:426, 542-598` — `companion object`의 `targetUrls`(일반 `ArrayList`)와 `lastProGress`, `currentProcessId`가 여러 `CoroutineScope(Dispatchers.IO)`에서 동기화 없이 접근/수정됨.
- **작업**: `Channel` 또는 `Mutex` 기반 순차 다운로드 큐로 전환하고, `targetUrls`를 스레드 안전 구조로 교체.
@@ -39,6 +39,8 @@ import io.realm.kotlin.internal.interop.sync.CancellableTimer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.Request
@@ -517,20 +519,19 @@ class ForeGroundService : Service() {
fun addToTargetYtubeUrl(url : String? = null, forMusic: Boolean = false) {
Blog.LOGE("url $url")
url?.let { url ->
if (url.length > 0) {
targetUrls.add(url to forMusic)
val nextTask = synchronized(targetUrls) {
url?.takeIf { it.isNotEmpty() }?.let {
targetUrls.add(it to forMusic)
}
targetUrls.removeFirstOrNull()
}
targetUrls.removeFirstOrNull()?.let {
downloadVideo(it.first,it.second)
nextTask?.let {
downloadVideo(it.first, it.second)
}
}
private val downloadMutex = Mutex()
@Volatile
var currentProcessId : String? = null
set(value) {
field = value
@@ -539,11 +540,13 @@ class ForeGroundService : Service() {
}
}
@Volatile
var lastProGress = -1f
fun downloadVideo(url: String?, forMusic: Boolean = false) {
url?.let {
CoroutineScope(Dispatchers.IO).launch {
try {
serviceScope.launch(Dispatchers.IO) {
downloadMutex.withLock {
try {
val baseDir = File(getExternalFilesDir(null), "completed_torrents")
// 2. youtube 전용 폴더 생성
@@ -601,11 +604,14 @@ class ForeGroundService : Service() {
Blog.LOGE("Error: ${response.err}")
} catch (e: Exception) {
Blog.LOGE("Download Error", e)
} finally {
currentProcessId = null
if ((targetUrls?.size ?: 0) > 0) {
val hasMore = synchronized(targetUrls) { targetUrls.isNotEmpty() }
if (hasMore) {
addToTargetYtubeUrl()
}
}
}
}
}
}
@@ -876,7 +882,7 @@ class ForeGroundService : Service() {
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
context.startActivity(launchIntent)
Blog.LOGE("애플뮤직 자동 실행 완료")
CoroutineScope(Dispatchers.Main).launch {
serviceScope.launch(Dispatchers.Main) {
delay(1500) // 1.5초 대기 (기기 속도에 따라 1000~2000 사이로 조절 가능)
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager