Practice make perfect


I’m a thread
the autobiography of a thread:birth,death and rebirth


I’m a thread

the autobiography of a thread:birth,death and rebirth

1.A newbie

I am a thread. I was born with a number 0x3704, and then led to a dark room where I found a lot of friends just like me.

My companion 0x6900 stayed here for a rather long time. He said to me in a sophisticated tone: “ The destiny of us thread is to deal with packages. You have to come back here as soon as you finish handling the package, or you may never come back.”

I asked innocently: “ Package ? What package? ”

“ Don’t worry, you’ll soon find out. We don’t raise idle ones here.”

It wasn’t long before the door opened. A ferocious guy yelled, “ 0x3704, come out! ”

A heavy package was pressed on me. There was also a paper listing operation steps.

“Go, deal with this package.”

“But where to? ”

“ Follow the instructions. First to the Runnable workshop.”

I found an arrow on the ground. It led me to a bright house, which already accommodated some threads. Everyone seemed nervous, ready to dash forward at any moment.

As soon as I came in, I heard the radio saying, “0x3704, enter the Running workshop.”

I walked faster. Someone was talking behind me.

“Such a luck dog! He can run right after being runnable! ”

“ Maybe he knows SOMEONE.”

“No. He has higher priority. Alas!”

Running workshop was right in front of me. It was so beautiful. No wonder the old thread kept nagging about how he wanted to stay here forever.

The room was bigger and had nicer views. The air was fresh and fragrant. There were many workers waiting to serve me.

They all had numbers. More importantly, they had tags saying “hard disk”, “database”, “memory”, “network card” and so on.

Just then I did not know about their job. Let’s check the operation steps.

Step one: Unpack the parameter.

There was a HttpRequest object inside, including two parameters: userName and password.

Step two: Perform login operation.

Well, someone was trying to login. I handed userName and password to the database waiter. He left slowly.

But why was he so slow? Anyway, I could stay here longer since the third step is not operable.

Just at this moment, the broadcast said “0x3704, this is CPU. Remember the step you are taking, and then leave with the package right away!”

I slowly began to clean up my things.

“Hurry up, the other thread is about to enter.”

I left this workshop and entered another big room, where many threads were drinking tea and playing cards with laziness.

“ Dude, you have nothing to do now?”

“You must be new here. I am waiting for the database waiter to give me my data. It is said that they are hundreds of thousands of times slower than us. Let’s have a good rest here.”

“How slow they are! I have someone here waiting to login, can they wait that long?”

“ Relax, don’t you know that a day in reality is equal to a year in CPU? Our time is counted by nanosecond and millisecond. As a result, a second in reality is equal to a couple of days in our world. We can definitely make it.”

Maybe I could get some sleep. Some time later, the loudspeaker started to work again: “0x3704, your data is coming, go and execute it!”

I turned and ran to the CPU workshop, only to find that it is a one-way door. I cannot get into the workshop through this door.

There was a roar of laughter from behind. “He is a newbie for sure. He doesn’t even know that we need to wait in the Runnable workshop!”

I hurried to the Runnable workshop. Being unlucky this time, I waited a long time before entering the CPU workshop.

While I was waiting, I heard people whispering.

“You know what, a thread was killed recently.”

“But why? ”

“That guy refused to leave the CPU workshop, causing the CPU utilization to remain 100%. So he was killed.”

“Where was he then? ”

“Maybe he was collected as a garbage.”

I secretly gave a shudder and worked faster. The second step was done.

Step three: Build the home page after successful login

This step was a bit time-consuming because there were a lot of HTML to deal with. Whoever wrote the code made it an annoying job for me to process.

While I was busy operating the HTML, CPU began to yell again.

“0x3704, this is CPU. Remember the steps you are taking, and then leave with the package right away!”

“Why should I? ”

“Each thread can only run on CPU for a while, and then it will be others’ turn. So go to the Runnable workshop and wait for your turn. ”

Then I have been switching among “runnable”, “waiting” and “running” for many times, and finally completed the work following the step list.

Finally, the package containing HTML was successfully sent back. As for what’s going on after login, I don’t care. It’s about to get back to my dark room. I felt a little unwilling.

But compared with some other threads, I am lucky enough. They are completely destroyed after operation, and I am still alive!

Back to the little black house, I was asked by the old thread 0x6900.

“How’s your first day?”

“The rules in our world are complex. First of all, you don’t know when is your turn; secondly, you may be interrupted at any time in the course of execution and asked to leave the CPU workshop; thirdly, once there are a time-consuming operation involving hard disk or database, you need to leave the CPU and wait; and fourthly, the chances are that you cannot start to work right away even if you have the data . You’ll have to wait for the CPU to pick.”

“Well enough, dude.”

“I just don’t understand why some threads died right after they complete their work, while we are still alive.”

“You know what, eternity is our prerogative. And we have an official name for our place: thread pool.”

2 . Making progress

As a thread, my daily life was made up by picking up packages, processing packages, and going back to thread pool, my dark home.

One day when I came back, I heard a brother saying, “Take a good rest today. Tomorrow will be a crazy day.” I checked the calendar, it is the fourth Friday of November tomorrow.

Sure enough, when the midnight bell rang, those human beings began to deliver packages crazily. In order to cope with the huge influx of packages, no one in the thread pool could idle down. All of us went out to deal with packages. The utilization rate of CPU workshop is super high. Hard disk was buzzing, network card lights flashing crazily. Although we worked very hard, packages still piled up quickly.

We can’t help it either. There are too many packages, mostly browsing pages, placing orders, buying, buying and buying.

The package mountain gradually disappeared. I could finally take a breath. I guess I will never forget today.

Through this, I realized that the world I live in is an electronic business network.

The job I do everyday is to deal with the login, browsing, shopping cart, orders and payment.

I asked the old worker 0x6900: “How long should we work? ”

“Until the system restarts.” said 0x6900.

“Have you ever been through system restart?”

“No. System restart will be our funeral elegy. It is the apocalypse. Once the system restarts, the whole thread pool will be destroyed. Time and space will all fade away. Everything starts all over again.”

“So when is it?”

“I cannot tell. Just enjoy your days.”

Life was in fact quite colorful. My favorite package was pictures uploading. Since the network was slow, I could stay in the CPU workshop for a long time and meet a lot of interesting threads.

For example, I met thread Memcached. He told me that with his help, the electronic business network saved many user data, and they are distributed in many machines.

I asked him, “No wonder the login operation becomes faster. It will be unnecessary to extract data from the database because you already have it. Oh, by the way, since you’re distributed, have you ever been to other machines?”

“No, I can only send a GET and PUT command to that machine through network to access the data. I know nothing else.”

Last time, while I was waiting, I met a thread working for database connection. Only by then did I realize that there was also a connection pool, almost exactly the same as our thread pool.

“Some packages are just so sick. They ask to look at the order data of a whole year, which is killing me,” he told me.

I said: “Come on, that is pure data for you. After you send those data, I have to build that into HTML, which is a lot sicker than your job!”

He then gave me an advice: “You must maintain a good relationship with Memcached so that we can take the data directly from him. Let’s try not to call the database so often. The life of us JDBC Connection will then be much easier.”

“Absolutely. The point is that you need to save the data in cache in advance, or I have to ask cache, find no data, and then turn to you again.”

This is life. If you don’t go and have some fun, how can your life become meaningful?

3 .Narrow escape

A few days ago, I experienced something terrible. I almost died outside the thread pool. In fact, I should have been able to anticipate that. I was very careless.

That day I dealt with some deposits and withdrawals from HTTP, and the old thread 0x6900 specifically told me: “You need to be very careful when dealing with these packages. You must get a lock first. Remember to lock the account when you deposit or withdraw money from it. Otherwise, other threads will break in and cause some damage. When I was young, my carelessness caused great trouble.

In order to “intimidate”, the kind-hearted 0x6900 gave me two tables as follows:

Bank account: Account A, the balance is 1000 $

Thread 1: Deposit

Thread 2: Withdraw

Table 1–1 The unlocked multithread


Table 1–2 The locked multithread


I was shocked: forgetting to lock the account can cause such a serious accident. From then on, whenever I saw the deposit and withdrawal package, I would deal with it with extreme carefulness. Luckily, there was no accident.

Today, I received a package for transferring money from a famous actor’s account to a famous director’s account. I would not disclose the name, but I could tell you that the amount of money was really huge.

As ordered by the old thread, I locked the account of the actor and then the account of the director.

But much to my surprise, there was another thread, yes, 0x7954, transferring money from the director’s account to the actor’s account at the same time.

Here’s the current situation:


At first I did not know what was going on. I waited and waited. Dozens of seconds went by and nothing happened. I had never experienced such an event before.

At this point I saw thread 0x7954. He sat there leisurely drinking coffee. I asked him:

“Dude, I see you drinking your eighth cup of coffee, why don’t you go and get your work done?”

“Well, you are having your ninth cup of tea. Why don’t you work?”

“I am waiting for a lock. Some asshole just won’t release it.”

“I am waiting for a lock too. If I know who is keeping it, I will beat him to death. ” 0x7954 replied fiercely.

I took a peek at him, only to find that HE is holding the lock of the director. It was exactly what I had been waiting for!

Obviously, 0x7954 also found that I was holding the lock that HE had been waiting for.

Soon the two of us got into a fight.

“Give me your lock and let me finish first!”

“No way. I will not release the lock until I finish my job. You cannot have it now!”

It only took few milliseconds for a quarrel to become actual fight.

More importantly, the two of us held not only the locks of this famous director and actor, but also many other locks. More and more threads joined the queue of waiting, and the onlookers packed the house. In the end, it became really a big deal. Our Big Boss “operating system”, who I had never seen before, was here. After all, Big Boss knew more. He looked at us, hummed, and said disdainfully:

“Dead lock again.”

“One of you will be killed. You two come here and draw lots.”

It just freaked me out. I drew lots in trepidation. Luckily, I survived.

After being forced to hand over all his resources, poor 0x7954 was unfortunately killed and vanished. I got the director’s lock and could get to work now. The Big Boss “operating system” disappeared like a gust of wind, only his voice followed:

“Remember, in our place, Director > Actor, which means that you need to get the director’s lock in the first place.”

Since there were not only director and actor here, but also many others, Big Boss left a table with an algorithm for calculating the size of the resource. After calculation, we need to get the lock from big to small:


(p.s.The calculation of the “size” of resource refers to making comparison between resources by turning them into numbers. For example, we can make comparison by the hascode of string.)

I went back to the thread pool. Everyone has heard about my adventure and kept asking me about details.

The evil-looking thread dispatcher put Big Boss’s algorithm on the wall.

Every morning, we had to stand right in front of the door, reciting out loud in a hilarious manner:

“Remember the order of resource locking. Remember to make comparison according to Boss’s algorithm. Remember to lock from the biggest to the smallest.”

4. Goodbye

Many days later, I and the other threads found a strange thing: the processing of packages was getting easier and easier. No matter it was login, browsing or saving money, the steps were the same. Everything will be returned to a fixed HTML page.

Once I glanced secretly and saw it reading: “ The system will be maintained and upgraded from 00:00 to 4:00 tonight. We are deeply sorry for the inconvenience.”

I told 0x6900 about it. He sighed:

“Alas, our life is at an end. The system will soon restart and we will disappear. Goodbye my brother.”

Then the moment finally came. I saw the things in the room disappeared one by one: the waiting workshop, Runnable workshop, and even the CPU workshop. There are fewer and fewer thread brothers around me. Finally, I am the only one left.

I yelled on the empty ground: “Is there anyone else?”

No reply.

This generation of thread pool has completed its mission.

However, the next generation is about to be reborn!