Thread pools

The creation of a new thread is a complex operation that takes up a lot of resources. In the Call stacks section, we covered how memory is allocated for a new thread. When the lower block of a function is removed from a stack, the thread is destroyed. To avoid constantly creating new threads, we can use thread pools. There is no logic in creating a new thread for invoking each short-term operation, because this operation and switching the program flow to a created context can take more time than executing the task itself. The thread-pool pattern assumes a class that contains a set of threads that are waiting for a new task, and a queue that holds the tasks.

The following diagram shows how this works:

The preceding diagram shows that a pool contains a queue that holds tasks submitted by producers. The threads from the pool take tasks from the queue and execute them.

Coroutines use thread pools under the hood. The java.util.concurrent package provides the functionality to create your own thread pools. The Executers class contains a lot of static factory functions to create a pool, as shown in the following screenshot:


The following example code demonstrates how to create and use a single-threaded executor:

fun main(args: Array<String>) {
val executor = Executors.newSingleThreadExecutor()
executor.submit { loadImage() }
executor.submit { loadImage() }
}

In the preceding snippet, we instantiated the executor variable and used the submit method to add a task to the queue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.31.125