okhttp: Authenticator breaking when refreshing tokens with coroutines runBlocking

Hi, I have this nondeterministic bug in production and I can’t pin it down with a minimal example My setup is okhttp, which drives Retrofit, which uses coroutines adapter I use Authenticator to refresh tokens and retry the requests, something like this

fun Authenticator.authenticate() {
	...
	synchronized(this) {
		runBlocking { retrofitService.suspendingRefreshTokens() }<--- 
		...
	}
}

What however SOMETIMES happens is that the api call just doesn’t finish, as if the coroutines were broken. I searched the internets and there seem to be some folks affected by this as well

https://stackoverflow.com/questions/62950438/using-coroutine-runblock-with-the-authenticator-to-handle-401-response-from-retr

Any intuition on what could be happening? I was thinking it was some sort of a deadlock because of the synchronized, however runBlocking seems to switch back to the original context, so it should be the same thread (atleast it appears that way in testing)

This never happened before with rxjava, where I used the same blockingGet() way to keep it blocking inside Authenticator; However rxjava retrofit adapter didn’t use the async parameter; which leads me to believe it possibly could be a issue with Okhttp’s threadpools somehow; rather than runBlocking? (which I also read is buggy)

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 6
  • Comments: 15

Most upvoted comments

Yes, a few workarounds are posted in the thread above. The simplest one is to use synchronous Call.execute() to refresh the token. 😉

I’ve just checked, await() and awaitResponse() produce a deadlock. 😦

Yes its used with runBlocking in the authenticator but such method in my code lives in some AuthApiClient which has login, logout and refresh methods, and I didnt want to have such asymetry (login suspending and refresh blocking), so I made them all suspending

Contrary to my comment above - the stackoverflow post concluded “Got it. Yeah I think that’s great advice: only use synchronous calls inside interceptors!”