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

rahulrav

07/08/2018, 5:29 PM
I am using coroutines on Google App Engine. I have a coroutine dispatcher which uses the defined executor:
Copy code
private fun defaultExecutor(): ThreadPoolExecutor {
    val maxPoolSize = Runtime.getRuntime().availableProcessors() * 3
    val keepAliveTime = 2L // in seconds
    val queue = LinkedBlockingQueue<Runnable>()
    return ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue, ThreadManager.currentRequestThreadFactory())
  }
Note the use of the
ThreadManager.currentThreadRequestFactory()
. Every time I invoke a
suspend
function I ensure that it is accompanied by a
withContext(...)
which uses the above defined coroutine dispatcher. I see that sometimes, I get `Exception`s on App Engine, claiming I am trying to get an instance of supporting services (like Datastore or Memcache) on a thread which was not created by their thread factory (
ThreadManager
). This typically happens in a coroutine's
resume
method. Any ideas on what I might be doing wrong ?
e

elizarov

07/08/2018, 5:39 PM
I cannot Google
currentThreadRequestFactory
. Can you given a link to its docs?
e

elizarov

07/08/2018, 6:43 PM
So it says
Returns a ThreadFactory that will create threads scoped to the current request.
It seems that you creating it in one request and reusing in another request
l

louiscad

07/08/2018, 6:57 PM
@rahulrav I think you should do the (inefficient but seemingly required) approach:
withContext(ThreadManager.currentRequestThreadFactory()) { ... /* Code accessing to the supporting services like Memcache or Datastore. */ }
r

rahulrav

07/08/2018, 11:21 PM
That makes sense. Thanks folks
7 Views