../executing-in-background-in-java-kotlin-android

Executing in Background in Java, Kotlin, Android

Table of contents

There are some recommendations about the methods chosen for executing a background task.

Ref: Background Task Overview, developer.android.

For a user-initiated background task, consider whether the task should be independent from the app process visibility.
For a user-initiated background task, consider whether the task should be independent from the app process visibility.
For an event-triggered background task, consider how much time the task would take.
For an event-triggered background task, consider how much time the task would take.

Besides methods decision, it is necessary to clear the difference between a thread and a coroutine. In one word, a thread can hold multiple coroutines, while a process can hold multiple threads.

Threads in Java

For single simple one, extend Thread and start it, or implement Runnable and put it in a thread and start.

For multiple threads, typically, create a ThreadPoolExecutor to manage multiple threads, or use its factory Executors to create one.

A Worker created in a thread pool is a Runnable , it is put into a thread when executing and a ReentrantLock is used to manage the workers. Specifically, the ReentrantLock is used to protect the manipulation of a HashSet<Worker> maintain in the thread pool.

Reference: Java线程池详解-线程池原理分析.

Coroutines in Kotlin

Kotlin Features and Reference (https://developer.android.com/kotlin/coroutines)

Coroutines execution are scheduled on multiple threads internally, internal implementation is sort of like a nice-wrapping executor service without bothering of creating and closing alike one. While Dispatchers provide some thread-level control before scheduling and executing a coroutine by specifying Default or IO, Main, guaranteeing some main-safe executing.

Basic usage

viewModelScope.launch(Dispatchers.IO) {
	// some blocking operations
	val jsonBody = “{xxx xxx}”
	loginRepository.makeLoginRequest(jsonBody)
}

viewModelScope::a CoroutineScope launch::create a coroutine on Dispatchers.IO if specified, or else on UI thread Dispatchers.IO::indicator of IO thread (type)

 				// Create a new coroutine on the UI thread
        viewModelScope.launch {
            val jsonBody = “{xxx xxx}”

						// Make the network call and suspend execution until it finishes
						// suspend here
            val result = loginRepository.makeLoginRequest(jsonBody)

            // Display result of the network request to the user
            when (result) {
                is Result.Success<LoginResponse> -> // Happy path
                else -> // Show error in UI
            }
        }

		    suspend fun makeLoginRequest(
		        jsonBody: String
		    ): Result<LoginResponse> {
		
		        // Move the execution of the coroutine to the I/O dispatcher
		        return withContext(Dispatchers.IO) {
		            // Blocking network request code
		        }
		    }

Readings

/Android/ /Note/ /Multi-Threads/ /Kotlin/