@@ -10,14 +10,22 @@ package io.velocitycareerlabs.impl.data.infrastructure.executors
1010import android.os.Handler
1111import android.os.Looper
1212import io.velocitycareerlabs.impl.domain.infrastructure.executors.Executor
13+ import io.velocitycareerlabs.impl.utils.VCLLog
1314import java.util.concurrent.ExecutorService
1415import java.util.concurrent.Executors
1516import java.util.concurrent.TimeUnit
1617
17- internal class ExecutorImpl : Executor {
18+ internal class ExecutorImpl : Executor {
19+
20+ private val TAG = ExecutorImpl ::class .simpleName
1821
1922 private val mainThread: Handler = Handler (Looper .getMainLooper())
20- private val backgroundThreadPool: ExecutorService = Executors .newFixedThreadPool(10 )
23+
24+ private var numberOfCores = Runtime .getRuntime().availableProcessors()
25+ private var optimalThreadCount = minOf(numberOfCores * 2 , 8 ) // Limit max to 8 threads
26+
27+ private val executorService: ExecutorService =
28+ Executors .newFixedThreadPool(optimalThreadCount, Executors .defaultThreadFactory())
2129
2230 override fun runOnMain (block : () -> Unit ) {
2331 mainThread.post {
@@ -26,13 +34,24 @@ internal class ExecutorImpl: Executor {
2634 }
2735
2836 override fun runOnBackground (block : () -> Unit ) {
29- backgroundThreadPool.submit {
30- block()
37+ executorService.submit {
38+ try {
39+ block()
40+ } catch (e: Exception ) {
41+ VCLLog .e(TAG , " " , e)
42+ }
3143 }
3244 }
3345
3446 override fun shutdown () {
35- backgroundThreadPool.shutdown()
36- backgroundThreadPool.awaitTermination(Long .MAX_VALUE , TimeUnit .SECONDS )
47+ executorService.shutdown()
48+ try {
49+ if (! executorService.awaitTermination(60 * 3 , TimeUnit .SECONDS )) {
50+ executorService.shutdownNow() // Force shutdown if not completed within 3 minutes
51+ }
52+ } catch (e: InterruptedException ) {
53+ executorService.shutdownNow() // Force shutdown on interruption
54+ Thread .currentThread().interrupt()
55+ }
3756 }
38- }
57+ }
0 commit comments