Home  >  Article  >  Java  >  Teach you to read jdk source code correctly

Teach you to read jdk source code correctly

little bottle
little bottleforward
2019-04-08 16:47:122581browse

This article mainly talks about how to read the source code of jdk itself. We will discuss the source code reading of various frameworks later.

The author believes that reading the source code mainly includes the following steps.

Setting goals

Everything has a purpose, and the same goes for reading source code.

From a large perspective, the purpose of reading source code is to improve our technical skills, apply them to work, quickly locate problems when encountering them, get promotions and salary increases, etc.

From a small perspective, the purpose of reading a certain piece of source code is to understand its principles, which is the stubbornness to explore the truth.

The purpose is abstract and the goal is specific. We must set a goal for ourselves before reading the source code.

For example, for ConcurrentHashMap, which we will study together in the next chapter, we can set the following goals:

(1) Familiar with the storage structure of ConcurrentHashMap;

(2) Familiar with The implementation process of the main methods in ConcurrentHashMap;

(3) Explore new technologies emerging in ConcurrentHashMap;

Ask questions

After we have the goal, we have to try to come up with some question.

Still taking ConcurrentHashMap as an example, the author raised the following questions:

(1) Are the data structures of ConcurrentHashMap and HashMap the same?

(2) When will HashMap have concurrency security issues in a multi-threaded environment?

(3) How does ConcurrentHashMap solve concurrency security issues?

(4) What locks does ConcurrentHashMap use?

(5) How is the expansion of ConcurrentHashMap performed?

(6) Is ConcurrentHashMap strongly consistent?

(7) What problems cannot be solved by ConcurrentHashMap?

(8) In addition to concurrency safety, what other differences does ConcurrentHashMap have from HashMap? Why does it need to be implemented in this way?

(8) What uncommon technologies are worth learning in ConcurrentHashMap?

How to ask questions

Many people will say, I also know to ask questions, but how to ask questions?

This is indeed a very difficult thing. I think there are three main points:

(1) Ask yourself

Treat yourself as the interviewer and ask yourself, go to death The kind asked in.

If you can’t ask yourself a few questions, it doesn’t matter. Please see below.

(2) Ask the Internet

There are many questions that you may not have thought of, so you need to go online and check related blogs to see if others have asked any questions.

Or, inquire about related interview questions.

For example, when I was learning the ConcurrentHashMap class, I checked online and many of them were based on jdk7. Then I can ask a question, what is the difference between the implementation of the ConcurrentHashMap class in jdk8 and jdk7? What optimizations has jdk8 made to jdk7?

(3) Keep discovering problems

It doesn’t matter if you can’t ask a few questions at the beginning. The key is to look. Only by looking can you find more problems.

Read the source code with questions, ignore unnecessary details, and focus on important details

First of all, be sure to read the source code with questions.

Secondly, be sure to ignore unnecessary details.

Again, be sure to stick to the important details.

At first glance, the last two steps seem to be contradictory. In fact, they are not. Ignoring unnecessary details is to avoid getting lost in the world of source code, and focusing on important details is to clarify the truth of the source code.

Whether you ignore the details here or stick to them depends mainly on their relevance to the problem.

The jdk source code is relatively easy to read. If you look at the spring source code later and cannot ignore unnecessary details, you will really get lost. Let’s lay a foreshadowing first~~

For example, I have read the readObject() method in the serialization-related code of ArrayList before.

<span style="font-family: 宋体, SimSun;">"s.readInt();"</span>What is this line of work for? Is it okay to omit it? At this time, you need to understand the knowledge related to serialization, and then look at the implementation in writeObject(). This is the code that you need to fight to death.

<span style="font-family: 宋体, SimSun;">"SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);"</span>What is this line for? At first glance, it seems that the code is related to permissions and has nothing to do with our problem of "serialization". Ignore it. If you really want to know, mark it first and study this thing after the serialization problem is solved.

private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
    // 声明为空数组
    elementData = EMPTY_ELEMENTDATA;

    // 读入非transient非static属性(会读取size属性)
    s.defaultReadObject();

    // 读入元素个数,没什么用,只是因为写出的时候写了size属性,读的时候也要按顺序来读
    s.readInt();

    if (size > 0) {
        // 计算容量
        int capacity = calculateCapacity(elementData, size);
        SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
        // 检查是否需要扩容
        ensureCapacityInternal(size);
        
        Object[] a = elementData;
        // 依次读取元素到数组中
        for (int i=0; i<size; i++) {
            a[i] = s.readObject();
        }
    }
}

Do more comparisons

When reading the jdk source code, it is also very important to do more comparisons. Comparisons can also be divided into horizontal comparisons and vertical comparisons.

(1) Horizontal comparison

is to compare with similar categories. For example, in the collection module, there are basically various insertions, queries, and deletions of elements. At this time, comparisons can be made from dimensions such as data structure and time complexity. This is a horizontal comparison.

(2) Vertical comparison

Can be compared from the history of collection development. For example, the development history of HashMap, from (single array) implementation (yes, you can directly use an array to implement HashMap), to (multiple array linked list) implementation, to (multiple array linked list red-black tree) implementation in jdk8, this It's a vertical comparison.

Do more experiments

The last step, the most important thing is to do more experiments.

For example, is ConcurrentHashMap strongly consistent?

You can start multiple threads to continuously call the get(), put(), and size() methods to see if there is strong consistency.

Patience & Persistence

I won’t say much about this, everyone knows it.

No matter what field you are in, patience & persistence are the most valuable qualities.

The same goes for reading the source code. As long as you persist patiently, you will eventually gain something.

[Recommended course: Java video tutorial]

The above is the detailed content of Teach you to read jdk source code correctly. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete