Java Interview Questions-Common Knowledge Points of ArrayList

Written before

There are many interview questions for ArrayList on the Internet, but most of them start from the data structure of ArrayList, such as the analysis of efficiency problems such as search and modification. This article wants to start from the perspective of concurrency and tell you how to answer the concurrency problem of ArrayList. .

Interview review

Generally, issues such as containers are more basic because they are generally investigated on one side, and this has also become a key factor in determining whether to enter the two sides.

Interviewer: I think you can master the basics of Java on your resume. Which containers have you used?

Me: Hello, interviewer. ArrayList, LinkedList, HashSet, hashMap, etc. are commonly used in general work.

Interviewer: Are they all thread-safe?

Me: It is not thread-safe, they will have thread-safety issues in high concurrency situations.

Interviewer: Can you write a program to briefly talk about the problems with ArrayList?

Of course, at this time, you must come up with a program that you usually accumulate.

I:

As follows: open 20 threads, each thread generates a random number, and adds the random number to the list container

public class ArrayListUnsafe {
    public static void main(String[] args) {
        List<String> lists = new ArrayList <>();
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                lists.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(lists);
            },String.valueOf(i)).start();
        }
    }
}

Under normal circumstances, this program will report java.util.ConcurrentModificationException, which is also a common error in high concurrency situations, concurrent modification exception

Interviewer: Why does this problem occur?

Me: In multithreading, each time you write data to the container, the order is not guaranteed. Whoever preempts the container starts to write the data. Therefore, there may be an overwrite situation, resulting in inconsistent results every time.

Interviewer: Is there any way to avoid this problem?

Me: Now jdk provides a variety of ways to ensure the thread safety of List.

Use the traditional Vector collection class. But this class adds the Synchronize keyword to the method to ensure thread safety. But jdK is no longer recommended, because the heavyweight locking method is used, resulting in low execution efficiency.
Use tools, Collections.synchronizedList to ensure thread safety. For example,
List lists = Collections.synchronizedList(new ArrayList <>());
Use the copy-on-write collection class. CopyOnWriteArrayList
can say copy-on-write, which is a bonus item, students! !

Interviewer: Can you briefly talk about what CopyOnWriteArrayList is?

Me: Copy-on-write is similar to separating the process of reading and writing data. such as

A thread and B thread both start to write data. Each time A and B write data, they need to obtain a license (similar to a lock). The data in the main memory is copied to the working memory and then modified. After the modification is completed Point the container reference to the new data set, and then allow other threads to modify it.

Source code

For example, for the add() method of copy-on-write, the jdk source code is as follows:

public boolean add(E e) {
    // 先获取锁,也就是前文说的许可证
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] elements = getArray();
        int len = elements.length;
        // 将原数组复制一份
        Object[] newElements = Arrays.copyOf(elements, len + 1);
        // 添加新值
        newElements[len] = e;
        // 将数组索引指向新数组
        setArray(newElements);
        return true;
    } finally {
        // 最后释放锁
        lock.unlock();
    }
}

Every time an element is added, the lock (that is, permission) is acquired first, and then the element is updated.

Answered to this level, the question of ArrayList is considered to be a better answer. If you can answer each question on one side, why and how to do it, it will be a matter of course to enter the second side.

Interviewer: Okay, that's all for today's interview. When will you have time for the next interview? Let me arrange it.

Hahaha, congratulations, the interview has been successfully won here, please prepare for both sides happily

Me: I have time these days, depending on your arrangements.

to sum up

There are many blogs describing the issue of containers. If you are interested in the underlying data structure of ArrayList, you can search for it yourself. This article mainly analyzes ArrayList interview questions from the perspective of thread safety, and how to answer them in general.

Finally, I will share my interview experience for many years. In the interview, you can answer a question according to the logic of the total score. First throw out the conclusion directly, and then demonstrate your conclusion with examples. Be sure to grasp the interviewer's heart for the first time, otherwise it is easy to give people the impression of not being able to grasp the key or marginal.

Guess you like

Origin blog.csdn.net/doubututou/article/details/112315548