https://kotlinlang.org logo
#coroutines
Title
# coroutines
k

kevin.cianfarini

06/10/2021, 7:43 PM
It’s failing with this output
Copy code
expected: Thread[test,5,main]
but was : Thread[main @coroutine#1,5,main]
u

uli

06/10/2021, 7:50 PM
I’d say it is the same thread. But i got renamed for diagnostic purpose
k

kevin.cianfarini

06/10/2021, 7:52 PM
How else might I be able to assert that they’re the same thread?
u

uli

06/10/2021, 7:52 PM
Try
Thread.currentThread().getId()
k

kevin.cianfarini

06/10/2021, 7:53 PM
nope, definitely different threads.
Copy code
expected: 21
but was : 1
It also fails while omitting the
UNDISPATCHED
start. I have edited the source example to simplify it further
u

uli

06/10/2021, 7:59 PM
Well, in general Dispatchers are not necessarily direct mappings to threads. Looks like TestCoroutineDispatcher is the proof for that then.
k

kevin.cianfarini

06/10/2021, 8:05 PM
cc @billjings
u

uli

06/10/2021, 8:07 PM
As a counter test you could check if it is dispatching away from your single threaded dispatcher
k

kevin.cianfarini

06/10/2021, 8:08 PM
Could you clarify? I believe your hypothesis to be true, which is why a plain old
runBlocking
works.
u

uli

06/10/2021, 8:30 PM
Copy code
@Test fun isolateFailing() = runBlocking(TestCoroutineDispatcher()) {
    var outerThread: Thread? = nullThread.currentThread()
    val singleThreadedContext = newSingleThreadContext("test")
    var innerThread: Thread? = null
    val function = suspend {
      outerThread = Thread.currentThread()
      innerThread = withContext(this@runBlocking.coroutineContext) {
        Thread.currentThread()
      }
    }

    val job = launch {
      withContext(singleThreadedContext) {
        function()
      }
    }

    job.join()
    assertThat(outerThread).isNotEqualTo(innerThread)
  }
k

kevin.cianfarini

06/10/2021, 8:36 PM
Yup, it’s not dispatching away from the single thread.
Copy code
expected not to be: Thread[test,5,main]
u

uli

06/10/2021, 8:39 PM
And it is free not to do so. No violation I guess
Just like unconfined dispatcher
k

kevin.cianfarini

06/10/2021, 9:01 PM
If this is the case, it’s a real shame this is undocumented functionality
Once I can confirm, I will make a PR
a

Adam Powell

06/11/2021, 1:31 AM
it is documented behavior:
Copy code
* By default, [TestCoroutineDispatcher] is immediate. That means any tasks scheduled to be run without delay are
 * immediately executed. If they were scheduled with a delay, the virtual clock-time must be advanced via one of the
 * methods on [DelayController].
3 Views