Author of this issue:

Video: Throwing line (Zhu Kai)

Article: Lewis (Yao Wenqin)

Hi, I’m Zhu Kai from throwline. Today is again a coroutine, but today is a little different:

  1. Today is the last installment of coroutines (at least for the near future);
  2. At the end of today’s video, I dui Kotlin official. It’s so exciting.

This post is about explaining what hanging non-blocking is all about, as well as a routine slap in the face for some of the most commonly misleading statements — not in the face, of course, I don’t have time for that, but just to give you a sense of fog.

To say more, watch the video:

Traditionally, I don’t know how to post a video in Nuggets, so you can go to Bilibili here, or you can go to YouTube here.

The following is from Lewis, the author of the article.

Hello, everybody. The last of the three qualities of coroutines is here. It’s easier to dig a hole than to fill it.

It’s been a really busy time, but we at the Android team have gained a new appreciation for what it means to code to school.

Friends who are in contact with large companies know that many companies will classify the sharing of some technologies as company secrets, which can only be shared internally. You can only see them after joining the company, and they cannot be shared with others. However, these classified secrets usually have the following characteristics:

  • After sharing, there are few updates, and many knowledge points are outdated
  • No specific business secrets involved, just don’t want people outside the company to learn
  • There is no technical exchange and no good technical community

I hope the above mentioned company is not in your company, there is no meaning of disS, so we want to do a good job of “code school”, but also hope that more peers with the same ambition to participate in the industry, through code school, we want to express the following technical concept:

  • The value of the article is not only the technical depth of this dimension, simple, find the essence is the key
  • This article is not a place to show off skills and lead wars, but a place for equal communication and mutual assistance
  • The tech community, like Android, is an ecosystem that needs to be maintained by everyone, not by everyone else

In the first two articles in the coroutine series, we introduced:

  • A coroutine is a threading framework
  • The suspended nature of coroutines is that threads cut out and cut back

It’s easy to forget because it’s a long time ago, but the concept of nonblocking that we’re going to talk about today, you don’t have to have a foundation in coroutines to understand it.

What is a “non-blocking suspend”

Non-blocking is relative to blocking.

Many of the concepts in programming languages come from life, just like jokes on talk shows.

Thread blocking is well understood. A real-world example is a traffic jam, which has three core points:

  • There’s an obstacle ahead, you can’t get through (thread stuck)
  • Need to wait for obstacles to clear before passing (time-consuming task end)
  • Unless you take a detour.

Semantically speaking, non-blocking suspension means non-blocking, which is one of the characteristics of suspension, that is, the suspension of coroutines is non-blocking, and coroutines don’t talk about blocking suspension.

When we talk about “non-blocking suspend”, it actually has several premises: it is not limited to one thread, because the suspension is inherently multithreaded.

Just like in the video, blocking is not blocking, this is all about single threads, but once you cut off the thread, it’s definitely not blocking, you’re running off to another thread, and the previous thread is free to do something else.

So by “non-blocking suspend,” we’re talking about cutting threads while the coroutine is suspended.

Why do we talk about non-blocking hangs

Since “non-blocking suspension” in article 3 is the same thing as “cutting threads” in article 2, is there any need to talk about it?

There is one. Because it’s written the same way as single-threaded blocking.

Coroutines are written to “look blocking” but are actually “non-blocking” because they do a lot of work inside them, and one of the things they do is cut threads for us.

The second one talks about hanging, and the point is that the tangent cuts past and then back.

The third article is about non-blocking. The main point is that threads cut, but they are written in much the same way as normal single threads.

Let’s take a look at the following example:

🏝️
main {
    GlobalScope.launch(Dispatchers.Main) {
        // 👇 Time-consuming operation
        val user = suspendingRequestUser()
        updateView(user)
    }
    
    private suspend fun suspendingRequestUser(a) : User = withContext(Dispatchers.IO) {
        api.requestUser()
    }
}
Copy the code

As you can see from the example above, the logic for time-consuming operations and updating the UI is put together like writing a single thread, but with a layer of coroutines outside.

And it was this coroutine that got rid of the fact that our single-threaded writing method would stall threads.

Nature of blocking

First of all, all code is blocking in nature, and only time-consuming code can cause human perceivable wait. For example, a 50 ms operation on the main thread will cause the interface to block several frames, which can be observed by our human eyes, and this is commonly referred to as “blocking”.

For example, when you develop an app that runs well on a good phone and freezes on a bad old phone, you’re saying the same line of code doesn’t take the same time.

In the video, there is an example of network IO. IO blocking is mostly reflected in “waiting”. Its performance bottleneck is data exchange with the network.

And this has nothing to do with coroutines, cutting threads can’t solve things, coroutines can’t solve.

Coroutines and threads

We talked about coroutines in three sessions, and Kotlin coroutines and threads can’t be separated from each other.

I won’t say anything else, but in Kotlin, a coroutine is a higher level tool API implemented on a thread, similar to Java’s Executor family of apis or Android’s Handler family of apis.

However, coroutines not only provide a convenient API, they are designed as a superframework based on threads, which you can interpret as new concepts to help you use the API better, but nothing more.

Just like ReactiveX, concepts like Observable have been built to make it easier for you to use the various operator apis.

With that said, the three big questions about Kotlin coroutines: what is a coroutine, what is a suspend, and what is the non-blocking form of a suspend are all covered. Very simple:

  • Coroutines are cutting threads;
  • Suspend is a cut thread that can automatically cut back;
  • Suspended non-blocking means that it can write non-blocking operations in code that looks blocking, simple as that.

Of course, these sentences are summaries, and the principles behind them must be grasped. If you forget, just go back and watch the previous videos and articles.

The video also corrects a mistake in the official document, which I won’t repeat here. Finally, I want to express one point:

Kotlin coroutines don’t create anything new without Kotlin or the JVM, they just make multithreaded development easier, something that came naturally with Kotlin’s birth. It’s grammatically magical, but in principle, it’s not magic.

I hope this series will help readers get started with Kotlin coroutines, and they will no longer feel afraid to get started. Please continue to pay attention to the follow-up articles of “Code on School” and look forward to making progress with you.

exercises

Implementing a network request using a coroutine:

  • Loading is displayed while waiting.
  • The request succeeds or an error makes Loading disappear;
  • The user is prompted that the request failed.
  • Make your coroutine look like a single thread.

The authors introduce

Video author

Throwing line (Zhu Kai)
  • Code school founder, project manager, content module planner and video content writer.
  • Android GDE (Google Certified Android Development Expert), former Flipboard Android Engineer.
  • GitHub Java ranks 92nd in the world, 6.6 K followers and 9.9 K stars on GitHub
  • MaterialEditText, a personal Android open source library, has been cited by several projects around the world, including Flipboard, a news-reading app with 500 million users worldwide.
  • I have been an Android instructor in Google Developer Group Beijing offline sharing sessions for several times.
  • After the release of the personal technical article “RxJava Details for Android Developers”, it was forwarded and shared in many domestic companies and teams and served as the main source of information for team technical meetings, as well as reverse spread to some Chinese teams in Some American companies such as Google and Uber.
  • HenCoder, the Android advanced teaching website founded by HenCoder, enjoys considerable influence in the Global Chinese Android development community.
  • After that, he founded HenCoder Plus, an Android advanced development teaching course, with students all over the world, including well-known first-tier Internet companies such as Ali, Toutiao, Huawei and Tencent, as well as senior software engineers from China’s Taiwan, Japan and the United States.

The authors

Lewis (Yao Wenqin)

Lewis (Wenqin Yao) is an Instant Android engineer. I joined Jike in 2017 and participated in the architecture design and product iteration of jike versions 4.0 to 6.0. With many years of Android development experience, I am now in charge of Android terminal multimedia infrastructure construction in Taiwan.