arrow-fx-coroutines / arrow.fx.coroutines / Resource / fromExecutor

fromExecutor

fun fromExecutor(f: suspend () -> ExecutorService): Resource<CoroutineContext>

Creates a single threaded CoroutineContext as a Resource. Upon release an orderly shutdown of the ExecutorService takes place in which previously submitted tasks are executed, but no new tasks will be accepted.

import arrow.fx.coroutines.*
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.max

suspend fun main(): Unit {
  val pool = Resource.fromExecutor {
    val ctr = AtomicInteger(0)
    val size = max(2, Runtime.getRuntime().availableProcessors())
    Executors.newFixedThreadPool(size) { r ->
      Thread(r, "computation-${ctr.getAndIncrement()}")
        .apply { isDaemon = true }
    }
  }

  pool.use { ctx ->
    listOf(1, 2, 3, 4, 5).parTraverse(ctx) { i ->
      println("#$i running on ${Thread.currentThread().name}")
    }
  }
}

Do you like Arrow?

Arrow Org
<