Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit ed722d57 authored by Ricki Hirner's avatar Ricki Hirner
Browse files

SyncManager: don't create worker threads when not necessary; shut Executor down after using it

parent 2d388eb3
Loading
Loading
Loading
Loading
+11 −8
Original line number Original line Diff line number Diff line
@@ -40,10 +40,7 @@ import at.bitfire.ical4android.Ical4Android
import at.bitfire.ical4android.TaskProvider
import at.bitfire.ical4android.TaskProvider
import at.bitfire.ical4android.UsesThreadContextClassLoader
import at.bitfire.ical4android.UsesThreadContextClassLoader
import at.bitfire.vcard4android.ContactsStorageException
import at.bitfire.vcard4android.ContactsStorageException
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.*
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import okhttp3.HttpUrl
import okhttp3.HttpUrl
import okhttp3.RequestBody
import okhttp3.RequestBody
import org.apache.commons.lang3.exception.ContextedException
import org.apache.commons.lang3.exception.ContextedException
@@ -91,10 +88,12 @@ abstract class SyncManager<ResourceType: LocalResource<*>, out CollectionType: L
     * We use our own dispatcher to make sure that all threads have [Thread.getContextClassLoader] set,
     * We use our own dispatcher to make sure that all threads have [Thread.getContextClassLoader] set,
     * which is required for dav4jvm and ical4j (because they rely on [ServiceLoader]).
     * which is required for dav4jvm and ical4j (because they rely on [ServiceLoader]).
     */
     */
    private val workDispatcher = Executors.newFixedThreadPool(
    private val _workDispatcher = lazy {
                // number of threads = number of CPUs, but max. 4
        Executors     // number of threads = number of CPUs, but max. 4
                min(Runtime.getRuntime().availableProcessors(), 4)
            .newFixedThreadPool(min(Runtime.getRuntime().availableProcessors(), 4))
            ).asCoroutineDispatcher()
            .asCoroutineDispatcher()
    }
    private val workDispatcher by _workDispatcher


    private val mainAccount = if (localCollection is LocalAddressBook)
    private val mainAccount = if (localCollection is LocalAddressBook)
        localCollection.mainAccount
        localCollection.mainAccount
@@ -113,6 +112,10 @@ abstract class SyncManager<ResourceType: LocalResource<*>, out CollectionType: L


    override fun close() {
    override fun close() {
        httpClient.close()
        httpClient.close()

        // shut down worker threads (only if the work dispatcher has been actually created)
        if (_workDispatcher.isInitialized())
            workDispatcher.close()
    }
    }