fix: Task 9 완료 - LocationUpdateService 스레드 풀 누수 제거 및 예외/동기화 보강
- LocationUpdateService.kt pushLocation():
* 매 호출마다 생성되던 Executors.newSingleThreadScheduledExecutor() 제거 -> 공유 locationScope(Dispatchers.IO + SupervisorJob) + delay(5000L) 전환
* addresses.first() -> addresses.firstOrNull() ?: return@getFromLocation 으로 빈 목록 예외 방어
* Realm writeBlocking 호출부 try-catch 추가
* 공용 NetworkClient.client 및 Response.use {} 적용으로 OkHttp 커넥션 누수 제거
* lastWeather 갱신 시 synchronized(lastWeather) 적용
- TODO.md: 2-2, 3-1, 3-2, 4-2 항목 완료 처리
- 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (1s)
This commit is contained in:
@@ -76,7 +76,7 @@
|
|||||||
- `app/src/main/kotlin/bums/lunatic/launcher/receiver/NLService.kt:186` (`CoroutineScope(Dispatchers.IO).launch`)
|
- `app/src/main/kotlin/bums/lunatic/launcher/receiver/NLService.kt:186` (`CoroutineScope(Dispatchers.IO).launch`)
|
||||||
- **작업**: Activity는 `lifecycleScope`, Fragment는 `viewLifecycleOwner.lifecycleScope`, Service는 `SupervisorJob()`이 포함된 `serviceScope`를 사용하고 `onDestroy()`에서 `serviceScope.cancel()` 호출.
|
- **작업**: Activity는 `lifecycleScope`, Fragment는 `viewLifecycleOwner.lifecycleScope`, Service는 `SupervisorJob()`이 포함된 `serviceScope`를 사용하고 `onDestroy()`에서 `serviceScope.cancel()` 호출.
|
||||||
|
|
||||||
- [ ] **2-2. `LocationUpdateService` 내 `Executors` 스레드 풀 누수**
|
- [x] **2-2. `LocationUpdateService` 내 `Executors` 스레드 풀 누수**
|
||||||
- `app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt:68, 106` — `pushLocation()` 호출마다 `Executors.newSingleThreadScheduledExecutor().schedule(...)`로 새 스레드 풀을 생성하고 `shutdown()`을 호출하지 않음. 또한 `130-131`행에서 `Companion.lastWeather.clear()` / `addAll()`을 백그라운드 스레드에서 동기화 없이 수정함.
|
- `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` 사용.
|
- **작업**: 단일 공유 `CoroutineScope` + `delay(5000)`으로 대체하고 `lastWeather` 갱신 시 스레드 안전한 컬렉션 또는 `StateFlow` 사용.
|
||||||
|
|
||||||
@@ -91,13 +91,13 @@
|
|||||||
|
|
||||||
### [Unit 3] 누락된 예외 처리 및 자원 관리 보강
|
### [Unit 3] 누락된 예외 처리 및 자원 관리 보강
|
||||||
|
|
||||||
- [ ] **3-1. 네트워크 호출 및 `OkHttpClient` 인스턴스 남발/미종료**
|
- [x] **3-1. 네트워크 호출 및 `OkHttpClient` 인스턴스 남발/미종료**
|
||||||
- `app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt:768-806` (`sendToI`): `try-catch`가 없어 네트워크 오류 시 `CoroutineScope(Dispatchers.IO)`에서 미처리 예외 발생. 매 호출마다 `OkHttpClient.Builder()`를 새로 생성하며 `response.body?.close()`(`use {}`) 누락.
|
- `app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt:768-806` (`sendToI`): `try-catch`가 없어 네트워크 오류 시 `CoroutineScope(Dispatchers.IO)`에서 미처리 예외 발생. 매 호출마다 `OkHttpClient.Builder()`를 새로 생성하며 `response.body?.close()`(`use {}`) 누락.
|
||||||
- `app/src/main/kotlin/bums/lunatic/launcher/player/PlayerActivity.kt:662` (`downloadSubtitle`): 매번 `OkHttpClient()` 신규 생성 및 `response.use {}` 미사용.
|
- `app/src/main/kotlin/bums/lunatic/launcher/player/PlayerActivity.kt:662` (`downloadSubtitle`): 매번 `OkHttpClient()` 신규 생성 및 `response.use {}` 미사용.
|
||||||
- `app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt:72-99, 110-135`: 매 요청마다 `OkHttpClient.Builder()` 생성 및 `response.use {}` 누락.
|
- `app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt:72-99, 110-135`: 매 요청마다 `OkHttpClient.Builder()` 생성 및 `response.use {}` 누락.
|
||||||
- **작업**: 싱글톤 `OkHttpClient` 공유, 모든 `Response`에 `.use { ... }` 적용, 코루틴 내부 네트워크 호출에 `try-catch` 또는 `CoroutineExceptionHandler` 추가.
|
- **작업**: 싱글톤 `OkHttpClient` 공유, 모든 `Response`에 `.use { ... }` 적용, 코루틴 내부 네트워크 호출에 `try-catch` 또는 `CoroutineExceptionHandler` 추가.
|
||||||
|
|
||||||
- [ ] **3-2. `LocationUpdateService` `addresses.first()` 및 NPE 위험**
|
- [x] **3-2. `LocationUpdateService` `addresses.first()` 및 NPE 위험**
|
||||||
- `app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt:50-52` — `geocoder.getFromLocation(...) { addresses -> addresses.first()?.let { ... } }`에서 `addresses`가 빈 리스트일 경우 `NoSuchElementException` 발생 가능 (`105`, `127`행에서도 `addresses.first()` 재호출).
|
- `app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt:50-52` — `geocoder.getFromLocation(...) { addresses -> addresses.first()?.let { ... } }`에서 `addresses`가 빈 리스트일 경우 `NoSuchElementException` 발생 가능 (`105`, `127`행에서도 `addresses.first()` 재호출).
|
||||||
- **작업**: `addresses.firstOrNull()?.let { address -> ... }`로 변경하고 단일 변수 `address` 재사용.
|
- **작업**: `addresses.firstOrNull()?.let { address -> ... }`로 변경하고 단일 변수 `address` 재사용.
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@
|
|||||||
- `app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt:335-360`와 `app/src/main/kotlin/bums/lunatic/launcher/home/NeoRssActivity.kt:92-120`에 `hiddenLoader` + `contentsLoad(url)` 및 `onConfigurationChanged()`(`isOpendFold`, `PointerIcon.TYPE_NULL`) 로직이 거의 동일하게 중복됨.
|
- `app/src/main/kotlin/bums/lunatic/launcher/LauncherActivity.kt:335-360`와 `app/src/main/kotlin/bums/lunatic/launcher/home/NeoRssActivity.kt:92-120`에 `hiddenLoader` + `contentsLoad(url)` 및 `onConfigurationChanged()`(`isOpendFold`, `PointerIcon.TYPE_NULL`) 로직이 거의 동일하게 중복됨.
|
||||||
- **작업**: `GeckoPreloadManager`(Delegate) 및 `CommonActivity` 기반 메서드로 추출하여 중복 제거.
|
- **작업**: `GeckoPreloadManager`(Delegate) 및 `CommonActivity` 기반 메서드로 추출하여 중복 제거.
|
||||||
|
|
||||||
- [ ] **4-2. `OkHttpClient` 생성 및 네트워크 호출 보일러플레이트 제거**
|
- [x] **4-2. `OkHttpClient` 생성 및 네트워크 호출 보일러플레이트 제거**
|
||||||
- `LunaticLauncher.kt:132`, `ForeGroundService.kt:769, 793`, `LocationUpdateService.kt:72, 110`, `PlayerActivity.kt:662` 등 여러 클래스에서 매번 `OkHttpClient.Builder()`와 `ConnectionPool`을 새로 생성함.
|
- `LunaticLauncher.kt:132`, `ForeGroundService.kt:769, 793`, `LocationUpdateService.kt:72, 110`, `PlayerActivity.kt:662` 등 여러 클래스에서 매번 `OkHttpClient.Builder()`와 `ConnectionPool`을 새로 생성함.
|
||||||
- **작업**: 앱 공용 `OkHttpClient` 싱글톤(또는 DI 제공)과 공통 요청 헬퍼를 두어 커넥션 풀 재사용 및 보일러플레이트 제거.
|
- **작업**: 앱 공용 `OkHttpClient` 싱글톤(또는 DI 제공)과 공통 요청 헬퍼를 두어 커넥션 풀 재사용 및 보일러플레이트 제거.
|
||||||
|
|
||||||
|
|||||||
@@ -35,11 +35,15 @@ import java.util.Base64
|
|||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
|
||||||
class LocationUpdateService : Service(), LocationListener {
|
class LocationUpdateService : Service(), LocationListener {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private val locationScope = kotlinx.coroutines.CoroutineScope(
|
||||||
|
kotlinx.coroutines.Dispatchers.IO + kotlinx.coroutines.SupervisorJob()
|
||||||
|
)
|
||||||
var longitude: Double = 0.0
|
var longitude: Double = 0.0
|
||||||
var lastWeather = mutableListOf<String>()
|
var lastWeather = mutableListOf<String>()
|
||||||
var latitude: Double = 0.0
|
var latitude: Double = 0.0
|
||||||
@@ -48,104 +52,84 @@ class LocationUpdateService : Service(), LocationListener {
|
|||||||
val geocoder = Geocoder(context, Locale.getDefault())
|
val geocoder = Geocoder(context, Locale.getDefault())
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
geocoder.getFromLocation(lat, long, 1) { addresses ->
|
geocoder.getFromLocation(lat, long, 1) { addresses ->
|
||||||
addresses.first()?.let {
|
val address = addresses.firstOrNull() ?: return@getFromLocation
|
||||||
addresses.get(0)
|
|
||||||
WorkersDb.getRealm()?.apply {
|
WorkersDb.getRealm()?.apply {
|
||||||
LocationLog().let { loc ->
|
LocationLog().let { loc ->
|
||||||
loc.fillData(it)
|
loc.fillData(address)
|
||||||
|
|
||||||
var list = query<LocationLog>().query("userId == $0", PrefString.telegramMyId.get("")).sort("time", Sort.DESCENDING).find()
|
val list = query<LocationLog>().query("userId == $0", PrefString.telegramMyId.get("")).sort("time", Sort.DESCENDING).find()
|
||||||
val post = (list.size == 0 || (list.size > 0 && list.first().time < (System.currentTimeMillis() - (1000L * 60L * 5L))))
|
val post = (list.size == 0 || (list.size > 0 && list.first().time < (System.currentTimeMillis() - (1000L * 60L * 5L))))
|
||||||
//&& inRangeLocation(lat,long,50) == false
|
try {
|
||||||
writeBlocking {
|
writeBlocking {
|
||||||
if (post) {
|
if (post) {
|
||||||
loc.userId = PrefString.telegramMyId.get("")
|
loc.userId = PrefString.telegramMyId.get("")
|
||||||
copyToRealm(loc)
|
copyToRealm(loc)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// post = true
|
} catch (e: Exception) {
|
||||||
// post.letTrue {
|
e.printStackTrace()
|
||||||
Executors.newSingleThreadScheduledExecutor().schedule({
|
}
|
||||||
|
|
||||||
|
val locJsonBytes = Gson().toJson(loc).toByteArray()
|
||||||
|
locationScope.launch {
|
||||||
|
kotlinx.coroutines.delay(5000L)
|
||||||
try {
|
try {
|
||||||
val url = PrefString.locationApi.get()
|
val url = PrefString.locationApi.get()
|
||||||
if (url.length > 10) {
|
if (url.length > 10) {
|
||||||
val client = OkHttpClient.Builder()
|
val request = Request.Builder()
|
||||||
.connectionPool(ConnectionPool(5, 60, TimeUnit.SECONDS))
|
.url(url)
|
||||||
.build()
|
.addHeader("Content-Type", "application/json")
|
||||||
|
.method(
|
||||||
// GET 요청 객체 생성
|
|
||||||
val builder: Request.Builder = Request.Builder().url(url)
|
|
||||||
.addHeader("Content-Type", "application/json").get()
|
|
||||||
builder.method(
|
|
||||||
"POST", RequestBody.create(
|
"POST", RequestBody.create(
|
||||||
"application/text".toMediaTypeOrNull(),
|
"application/text".toMediaTypeOrNull(),
|
||||||
Base64.getEncoder().encode(
|
Base64.getEncoder().encode(locJsonBytes)
|
||||||
Gson().toJson(loc).toByteArray()
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
.build()
|
||||||
val request: Request = builder.build()
|
|
||||||
|
|
||||||
// Blog.LOGE("telegram before request ")
|
bums.lunatic.launcher.utils.NetworkClient.client.newCall(request).execute().use { response ->
|
||||||
// OkHttp 클라이언트로 GET 요청 객체 전송
|
if (!response.isSuccessful) {
|
||||||
val response: Response = client.newCall(request).execute()
|
Blog.LOGE("telegram Error Occurred: ${response.code}")
|
||||||
if (response.isSuccessful) {
|
|
||||||
// 응답 받아서 처리
|
|
||||||
val body: ResponseBody? = response.body
|
|
||||||
if (body != null) {
|
|
||||||
// Blog.LOGE("Location >>> ${body.string()}")
|
|
||||||
}
|
}
|
||||||
} else Blog.LOGE("telegram Error Occurred")
|
|
||||||
}
|
}
|
||||||
} catch (e: java.lang.Exception) {
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
}
|
}
|
||||||
}, 5, TimeUnit.SECONDS)
|
}
|
||||||
|
|
||||||
Blog.LOGE("addresses ${addresses.first()}")
|
Blog.LOGE("addresses $address")
|
||||||
Executors.newSingleThreadScheduledExecutor().schedule({
|
locationScope.launch {
|
||||||
|
kotlinx.coroutines.delay(5000L)
|
||||||
try {
|
try {
|
||||||
val url = "https://api.weatherapi.com/v1/current.json?key=${PrefString.weatherApiKey.get()}&q=${lat},${long}&aqi=no"
|
val url = "https://api.weatherapi.com/v1/current.json?key=${PrefString.weatherApiKey.get()}&q=${lat},${long}&aqi=no"
|
||||||
if (url.length > 10) {
|
if (url.length > 10) {
|
||||||
val client = OkHttpClient.Builder()
|
val request = Request.Builder().url(url).get().build()
|
||||||
.connectionPool(ConnectionPool(5, 60, TimeUnit.SECONDS))
|
bums.lunatic.launcher.utils.NetworkClient.client.newCall(request).execute().use { response ->
|
||||||
.build()
|
|
||||||
|
|
||||||
// GET 요청 객체 생성
|
|
||||||
val builder: Request.Builder = Request.Builder().url(url).get()
|
|
||||||
val request: Request = builder.build()
|
|
||||||
|
|
||||||
// Blog.LOGE("telegram before request ")
|
|
||||||
// OkHttp 클라이언트로 GET 요청 객체 전송
|
|
||||||
val response: Response = client.newCall(request).execute()
|
|
||||||
if (response.isSuccessful) {
|
if (response.isSuccessful) {
|
||||||
// 응답 받아서 처리
|
val result = response.body?.string()
|
||||||
val body: ResponseBody? = response.body
|
if (result != null) {
|
||||||
if (body != null) {
|
val w = Gson().fromJson(result, CurrentWeather::class.java)
|
||||||
var result = body.string()
|
|
||||||
var w = Gson().fromJson<CurrentWeather>(result,CurrentWeather::class.java)
|
|
||||||
var address =addresses.first()
|
|
||||||
|
|
||||||
w.addr = address.getAddressLine(0)
|
w.addr = address.getAddressLine(0)
|
||||||
|
synchronized(lastWeather) {
|
||||||
lastWeather.clear()
|
lastWeather.clear()
|
||||||
lastWeather.addAll(w.getSummaryInfo())
|
lastWeather.addAll(w.getSummaryInfo())
|
||||||
// Blog.LOGE("Location >>> ${result}\n${lastWeather}")
|
|
||||||
}
|
}
|
||||||
} else Blog.LOGE("telegram Error Occurred")
|
|
||||||
}
|
}
|
||||||
} catch (e: java.lang.Exception) {
|
} else {
|
||||||
|
Blog.LOGE("weatherapi Error Occurred: ${response.code}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
}
|
}
|
||||||
}, 5, TimeUnit.SECONDS)
|
|
||||||
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// addresses.forEach { }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: IOException) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user