# Coroutines: Force execution on certain thread

**URL:** <https://discuss.kotlinlang.org/t/coroutines-force-execution-on-certain-thread/15766>\
**Category:** Support\
**Created:** [January 7, 2020, 4:14pm UTC](https://discuss.kotlinlang.org/t/coroutines-force-execution-on-certain-thread/15766 "2020-01-07T16:14:44Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![westnordost](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/westnordost/32/6008_2.png) [@westnordost](https://discuss.kotlinlang.org/u/westnordost)\
**Post date:** [January 7, 2020, 4:14pm UTC](https://discuss.kotlinlang.org/t/coroutines-force-execution-on-certain-thread/15766/1 "2020-01-07T16:14:44Z")

</div>

So, I have a certain piece of code that must be executed on a certain Android _[HandlerThread](https://developer.android.com/reference/android/os/HandlerThread)_ and should return a result. In a nutshell, a _HandlerThread_ is a thread that contains an endless loop and processes a queue of posted runnables.

I would like to achieve that I have a suspending function within a class that implements _CoroutineScope_ like this:

```
suspend fun createFoo(): Foo {
    // create foo on certain HandlerThread and return suspending
}

```

So, my initial thought was that there may be a builder for a CoroutineDispatcher in the kotlinx-coroutines-android library that lets me select a _HandlerThread_ like this:

```
suspend fun createFoo(): Foo {
    return withContext(HandlerContext(myHandler)) {
        doThingToCreateFoo()
    }
}

```

But there isn’t. (Not sure if _withContext_ would be correct here anyway). So, I was thinking I use a Future that I launch in the mentioned thread and await the result, like this:

```
suspend fun createFoo(): Foo {
    val result = FutureTask<Foo>(Callable { doThingToCreateFoo() })
    myHandler.post { result.run() }
    val deferred = async { result.get() } // .get blocks the current thread until a result is available
    return deferred.await()
}

```

I am not sure if this behaves as I expect it to behave at all, and also from the IDE (IntelliJ) get two warnings I don’t understand:

- For async: "Ambiguous coroutineContext due to CoroutineScope receiver of suspend function
- For FutureTask.get: “Inappropriate blocking method call”

So, maybe someone can help me and explain what I got wrong.

---

<div class="post-metadata">

**Author:** ![nickallendev](https://avatars.discourse-cdn.com/v4/letter/n/cdc98d/32.png) [@nickallendev](https://discuss.kotlinlang.org/u/nickallendev)\
**Post date:** [January 7, 2020, 5:08pm UTC](https://discuss.kotlinlang.org/t/coroutines-force-execution-on-certain-thread/15766/2 "2020-01-07T17:08:35Z")

</div>

The method you want is [asCoroutineDispatcher](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-android/kotlinx.coroutines.android/android.os.-handler/as-coroutine-dispatcher.html).

```auto
withContext(myHandler.asCoroutineDispatcher()) {
   createFoo() 
} 

```

---

<div class="post-metadata">

**Author:** ![nickallendev](https://avatars.discourse-cdn.com/v4/letter/n/cdc98d/32.png) [@nickallendev](https://discuss.kotlinlang.org/u/nickallendev)\
**Post date:** [January 7, 2020, 7:10pm UTC](https://discuss.kotlinlang.org/t/coroutines-force-execution-on-certain-thread/15766/3 "2020-01-07T19:10:30Z")

</div>

As for the errors:

Dispatchers are like handlers except they can use a thread pool. Blocking calls block threads in the pool from doing work. Block all of them and you can even deadlock. Suspending calls simply return early under the covers so the event loop can continue and then resume by posting a task back to the event loop. So avoid blocking calls in coroutines except for on the IO dispatcher which is designed for them (it always creates new threads when needed so it never is completely blocked).

I’d need more context to understand the other error completely. I’m guessing you just want to explicitly specify the `this` that you want to call `async` on.

---

<div class="post-metadata">

**Author:** ![westnordost](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/westnordost/32/6008_2.png) [@westnordost](https://discuss.kotlinlang.org/u/westnordost)\
**Post date:** [January 8, 2020, 4:01pm UTC](https://discuss.kotlinlang.org/t/coroutines-force-execution-on-certain-thread/15766/4 "2020-01-08T16:01:51Z")

</div>

Thank you for the info!

So generally, how would one go about transforming blocking stuff (waiting for HTTP answer, DB access etc) to a suspending function? For example, I guess

```
suspend fun sleep() {
    Thread.sleep(1000)
}

```

is not ok, but what would be? Wrap it in `withContext(Dispatchers.IO) { ... }` ?

Regarding the warning on FutureTask, I guess this was related to that since `FutureTask.get()` blocks, there should be some kind of handling for interrupt. The warning didn’t give much more context.

---

<div class="post-metadata">

**Author:** ![emanguy](https://avatars.discourse-cdn.com/v4/letter/e/c0e974/32.png) [@emanguy](https://discuss.kotlinlang.org/u/emanguy)\
**Post date:** [January 15, 2020, 2:25pm UTC](https://discuss.kotlinlang.org/t/coroutines-force-execution-on-certain-thread/15766/5 "2020-01-15T14:25:12Z")

</div>

If you HAVE to call a blocking method, you should switch to the IO dispatcher with withContext as you proposed. However, if possible you should break up your coroutines by returning control to the thread either by using `delay()` to suspend your function for some time or by invoking `yield()` to return control to the thread without a delay. Note that both delay() and yield() will throw `CancellationException` when the coroutine is cancelled, so using these will allow you to support cancellation automatically.

For example, reading a stream could be done asynchronously AND support cancellation by doing the following:

```
suspend fun readStream(stream: FileInputStream) {
    var nextByte = stream.read()
    // -1 is returned when there's nothing left in the file
    while (nextByte != -1) {
        print(nextByte.toChar())
        yield() // Return control to the worker thread, IRL you may want to do this less frequently
        nextByte = stream.read()
    }
}

```

---

<div class="post-metadata">

**Author:** ![nickallendev](https://avatars.discourse-cdn.com/v4/letter/n/cdc98d/32.png) [@nickallendev](https://discuss.kotlinlang.org/u/nickallendev)\
**Post date:** [January 17, 2020, 7:01am UTC](https://discuss.kotlinlang.org/t/coroutines-force-execution-on-certain-thread/15766/6 "2020-01-17T07:01:46Z")

</div>

`FileInputStream.read` is a blocking call. Please do not call it in a coroutine with out using `Dispatchers.IO`. It is no different than any other IO.
