final finally finalize difference stream stream Stream method mvc aop ioc understanding the difference between Collection and Collections Nacos AP, CP

Method to create thread

1. The class inherits Thread and overrides the run() method
2. The class implements the Runnable interface and overrides the run() method (no return value, no exception will be thrown)

3. Implement the Callable interface and implement the call() method (with a return value and an exception will be thrown)

To customize the thread pool, you can use the hutool tool

ExecutorBuilder.create().build builder mode

What are the advantages of SpringBoot over SSM

1. Simplify configuration

2. Rapid development, built-in tomcat server

3. Microservice support: Spring Boot is an ideal choice for building a microservice architecture. It provides seamless integration with Spring Cloud and can easily implement microservice-related functions such as service registration and discovery, load balancing, and circuit breakers.

Spring Boot has obvious advantages over the SSM framework in terms of development efficiency, simplified configuration, and microservice support, allowing developers to build efficient and scalable applications more quickly.

Design pattern

The underlying principle of HashMap

In jdk1.8, HashMap consists of array (the backbone of the array composed of key-value entries) + linked list (when there are too many elements, it is used to resolve hash conflicts. Multiple elements on one element of the array linked list composed of entries) + Red-Black Tree (when the number of elements in the linked list reaches 8, the linked list storage is changed to red-black tree storage) for data storage. When the length of the array is greater than 64 and the nodes of the linked list reach 8, it will be converted into a red-black tree. When the nodes of the red-black tree are less than 6, it is converted into a linked list.

Loading factor: 0.75

Initial capacity: 16

Expansion multiple: 2

Implementation principle of map.put(k,v)

1. First encapsulate k and v into Node objects (nodes).

2. Then its bottom layer will call K’s hashCode() method to get the hash value.

3. Convert the hash value into the subscript of the array through the hash table function/hash algorithm. If there is no element at the subscript position, add the Node to this position. If there is a linked list at the position corresponding to the subscript. At this time, k will be equal to the k of each node on the linked list. If all equals methods return false, then the new node will be added to the end of the linked list.

The difference between HashMap and Hashtable

HashMap and Hashtable are both implementation classes under the Map interface. Map objects are key-value pairs, so the two classes are also key-value pairs.

The initial capacity of HashMap is 16, and the initial capacity of Hashtable is 11.

Hashtable is thread-safe and uses synchronized synchronization code blocks to ensure safety and low efficiency.

HashMap is non-thread-safe and highly efficient. If you want to use it in a multi-threaded scenario, please use ConcurrentHashMap.

key value: HashMap key value can be null, HashTable is not allowed to be null

HashMap and Hashtable

Storage: HashMap operates with null keys and values, while Hashtable does not allow this.

Thread safety: Hashtable is thread-safe, while HashMap is not thread-safe.

Recommended use: As you can see in the class annotation of Hashtable, Hashtable is a reserved class and is not recommended for use. It is recommended to use HashMap instead in a single-threaded environment. If multi-threaded use is required, use ConcurrentHashMap instead.

What is the difference between Array and ArrayList

Array can store basic data types and objects, while ArrayList can only store objects.

Array is specified with a fixed size, while ArrayList size is automatically expanded.

Array does not have as many built-in methods as ArrayList. For example, only ArrayList has methods such as addAll, removeAll, and iteration.

The difference between ArrayList and LinkList

1. Data structure: ArrayList is implemented based on dynamic arrays. It stores elements through arrays and can quickly access elements based on indexes. LinkedList is implemented based on a doubly linked list, which stores elements through links between nodes. To access elements, you need to traverse from the beginning or the end.

2. Insertion and deletion operations: When inserting or deleting elements in the middle of ArrayList, subsequent elements need to be moved because the elements of the array are stored continuously. When LinkedList inserts or deletes an element in the middle, it only needs to adjust the links of the previous and next nodes, which is more efficient.

3. Memory usage: ArrayList takes up more space in memory than LinkedList, because ArrayList needs to pre-allocate a certain size of array space. Each element of LinkedList requires additional space to store references to the preceding and following nodes.

To sum up, when frequent insertion and deletion operations are required and the requirements for random access are not high, you can choose LinkedList. When the requirements for random access are high and insertion and deletion operations are rare, ArrayList can be selected.

ThreadLocal related issues

What is ThreadLocal?

ThreadLocal is a thread local variable in Java that can be used to store the private data of each thread. Each thread has its own ThreadLocal variable. The data between different threads are isolated from each other and will not interfere with each other.

What is the implementation principle of ThreadLocal?

Each ThreadLocal has a ThreadLocalMap object that stores all ThreadLocal variables and corresponding values. The values in the corresponding ThreadLocalMap can be accessed through the get() and set() methods of the ThreadLocal object.

Usage scenarios?

After token verification, the user-related information is stored in ThreadLocal to facilitate subsequent business acquisition of current user information. Full link tracking, transaction status

Note:

When using ThreadLocal, you need to pay attention to the problem of memory leaks. When a thread ends, you need to manually clear the corresponding ThreadLocalMap to avoid memory leaks (it is a weak reference)

Fragmentary knowledge points

What is MVCC

Multiversion Concurrency Control Multiversion high concurrency control is designed by InoDB to solve the repeatable read problem in the MySQL transaction isolation level. It solves the repeatable read problem through version control.

bitmap

The basic idea of Bit-map is to use a bit to mark the Value corresponding to an element, and the Key is the element. Since data is stored in Bit units, storage space can be greatly saved. (save storage space)

Bitmaps support storing information by bits and can be used to implement Bloom filters.

What functions does reflect provide

Reflection is a mechanism for obtaining and manipulating program structures at runtime. The reflection mechanism in Java allows the program to dynamically obtain class information at runtime, and use this information to instantiate objects, call methods, access properties, etc.

1. You can obtain class information, including class methods, attributes, constructors, etc.

2. Dynamically create objects: create objects through reflection mechanism

3. Dynamic calling methods: You can dynamically call object methods, including private methods, through the reflection mechanism.

4. Access and modify object fields

AOP transactions and JDBC all use reflection

What are the ways to create objects?

1. Use the keyword new to create an object instance through the constructor.

2. Use the reflection mechanism to call the newInstance() method of the Class class.

3. Use the reflection mechanism to call the newInstance() method of the Constructor class.

4. Using deserialization, read a byte stream and convert it into an object instance.

5. By cloning, create a new object that is exactly the same as the original object. Object.clone()

6. Use the factory method pattern to create object instances from the factory class. beanFactory

JS for array deduplication

1. The array can be converted to a set, and finally converted to an array.

2. Use indexOf to remove duplicates

Loop through the original array, use indexof to determine whether the current element exists in the host, and if not, push it to the new array

Thread pool life cycle

1. Initial state

2. Running status

3. Blocked state

4. Closed state

5. Stop state

6. Termination status

What is the RPC framework

The RPC framework is a software framework that implements the RPC protocol, allowing developers to easily make remote calls across the network. Calling remote methods is like calling local methods. Common rpc frameworks include dubbo, spring cloud, gRPC, etc.

final finally finalize difference

1. Final: You can modify classes, variables, and methods. Modified class means that the class cannot be inherited, modified method means that the method cannot be overridden, and modified variable means that the variable is a constant and cannot be reassigned.

2. Finally: Generally used in the try-catch code block. When handling exceptions, we usually put the code method that must be executed in the finally code block, which means that the code block will be executed regardless of whether an exception occurs. It is generally used to store Some code to close resources

code.

3. finalize: a method belonging to the Object class, and the Object class is the parent class of all classes. This method is generally called by the garbage collector. When we call the System.gc() method, the garbage collector calls finalize( ), garbage collection, the final judgment of whether an object is recyclable.

Talk about the understanding of stream

Stream is a data stream used to process data in a program. It provides a continuous and ordered data flow, and various operations can be performed on the data in it, such as filtering, mapping, sorting, etc.

Stream streams can operate on data sources such as collections, arrays, and I/O channels. The use of Stream can greatly simplify the code and improve the readability and maintainability of the code. It can replace traditional loops and conditional statements, making the code more concise and elegant.

Commonly used methods in Stream

In Java, Stream operation stream is a newly introduced function in Java 8. It provides many powerful operations to facilitate us to process and operate collections. Commonly used Stream operations include:

1. Filter: Use the filter() method to filter out elements in the collection that do not meet the conditions.

2. Mapping: Use the map() method to map each element in the collection.

3. Sorting: Use the sorted() method to sort the elements in the collection.

4. Deduplication: Use the distinct() method to remove duplicate elements in the collection.

5. Statistics: Use the count() method to count the elements in the collection.

6. Aggregation: Use the reduce() method to perform aggregation calculations on the elements in the set.

7. Traversal: Use the forEach() method to traverse every element in the collection.

8. Matching: Use anyMatch(), allMatch(), noneMatch() methods to determine the matching of elements in the collection.

9. Grouping: Use the qroupingBy() method to group by a certain attribute.

10. Conversion: Use the collect() method to convert elements in a collection into another collection.

11. Average: The average() method can be used to calculate the average of a set of elements.

 @Test
    void contextLoads() {
        List<User> users = new ArrayList<>();
        users.add(new User("Yinlang", 20, "Male", "Beijing", 1200));
        users.add(new User("Kafka", 28, "Female", "Beijing", 2100));
        users.add(new User("Edge", 27, "Male", "Shanghai", 7800));
        users.add(new User("Xueyi", 30, "Female", "Shanghai", 2600));
        users.add(new User("Jackdaw", 24, "Female", "Suzhou", 2800));
        users.add(new User("Xier", 29, "Female", "Suzhou", 2000));
        //Group by city
       /* Map<String, List<User>> collect = users.stream().collect(Collectors.groupingBy(User::getCity));
        collect.forEach((k, v) -> {
            System.out.println("City:" + k);
            System.out.println("Collection:" + v);
        });*/
        //List the sales champions in each city
/* Map<String, Optional<User>> map = users.stream().collect(
                Collectors.groupingBy(
                        User::getCity,
                        Collectors.maxBy(Comparator.comparingInt(User::getMoney))
                )
        );
        map.forEach((k, v) -> {
            System.out.println("City:" + k);
            System.out.println("Pin crown:" + v);
        });*/
        //Find the total sales amount in each city
 /* Map<String,Integer> sum=users.stream().collect(Collectors.groupingBy(User::getCity,Collectors.summingInt(User::getMoney)));
        sum.forEach((k, v) -> {
            System.out.println("City:" + k);
            System.out.println("Total sales:" + v);
        });*/
        //Total sales nationwide
      /* Integer collect = users.stream().collect(Collectors.summingInt(User::getMoney));
        System.out.println("National total sales:" + collect);*/
        //Filter out employees greater than 22
   /* List<User> age=users.stream().filter(s->s.getAge()>22).collect(Collectors.toList());
        System.out.println(age);*/
        // sales amount of best and worst employees
 /* User user = users.stream().max(Comparator.comparing(User::getMoney)).get();
        User user1 = users.stream().min(Comparator.comparing(User::getMoney)).get();
        Integer integer = users.stream().map(User::getMoney).max(Integer::compareTo).get();
        System.out.println("Maximum salary:" + integer);
        System.out.println("Maximum salary:" + user);
        System.out.println("Minimum wage:" + user1);*/
        //Per capita sales amount
        double asDouble = users.stream().mapToDouble(User::getMoney).average().getAsDouble();
        System.out.println("Sales per capita:" + asDouble);
        //Sort nationwide based on sales amount
        users.sort(Comparator.comparing(User::getMoney).reversed());
        System.out.println(users);
        //How many sales cities are there in the country?
        List<String> collect = users.stream().map(User::getCity).distinct().collect(Collectors.toList());
        System.out.println(collect);
        List<String> correctAnswers = new ArrayList<>();
        List<String> userAnswers = new ArrayList<>();
        correctAnswers.add("a");
        correctAnswers.add("b");
        correctAnswers.add("c");
        userAnswers.add("a");
        userAnswers.add("b");
        userAnswers.add("c");
        //userAnswers.add("d");
        if (userAnswers.size() == correctAnswers.size() & amp; & amp; correctAnswers.containsAll(userAnswers)) {
            System.out.println("The answer is correct");
        } else {
            System.out.println("Wrong answer");
            // System.out.println(b);
        }
    }

Talk about the understanding of mvc aop ioc

ioc Inversion of Control We hand over the original process of creating objects to spring, which can achieve decoupling between objects.

aop enhances the business without changing the original code

The difference between Collection and Collections

Collection is the superior interface of the collection class, and the interfaces inherited from it mainly include Set and List.

Collections is a helper class for collection classes. It provides a series of static methods to implement operations such as searching, sorting, and thread safety for various collections.

What do Nacos AP and CP mean (the default is AP)

AP and CP in Nacos are concepts from CAP theory. CAP theory is an important theory in distributed system design. It points out that for a distributed system, the three characteristics of Consistency (consistency), Availability (availability) and Partition tolerance (partition fault tolerance) cannot be satisfied at the same time.

In CAP theory:

Consistency: Whether all data copies in a distributed system have the same value at the same time (equivalent to all nodes accessing the same latest data copy).

Availability: After a part of the nodes in the cluster fails, whether the entire cluster can still handle the client’s read and write requests. (High availability for data updates)

Partition tolerance: Network partition refers to whether the system can still operate normally when the network is interrupted.

In Nacos, AP mode and CP mode represent different features:

AP mode: In this mode, Nacos prioritizes availability and partition fault tolerance. In other words, even though the data may be inconsistent on some nodes, users can get the configuration from Nacos at any time. This is the default mode of Nacos.

CP mode: In this mode, Nacos gives priority to ensuring consistency and partition fault tolerance. In other words, in order to ensure that the data of all nodes is consistent, Nacos may sacrifice part of the availability, that is, some requests may fail in the case of network partitions.

In actual use, you can choose to use AP mode or CP mode according to business needs and scenarios.

The difference between run() and start()

When the run() method is called directly, the task code is executed in the current thread; when the start() method is called, a new thread is created and the task code is executed in the new thread.

What is the difference between parallelism and concurrency

Parallelism: Multiple processors execute multiple instructions at the same time.

Concurrency: refers to a processor, that is, multiple tasks are executed alternately in different time periods.

The difference between threads and processes

Process: Process is the basic unit of program running and resource allocation. A program has at least one process, and a process has at least one thread, but a process generally has multiple threads.

Thread: Thread is the basic unit of CPU scheduling and dispatch. In the actual development process, multi-thread concurrency is generally considered.

What is thread deadlock? How does deadlock occur? How to avoid deadlock?

Thread deadlock refers to the fact that two or more threads hold the resources required by each other, causing these threads to be in a waiting state and unable to execute.

How does a deadlock occur?

1. Mutually exclusive condition, a resource can only be held by one thread.

2. Maintaining conditions: When a thread requests a resource, if it already holds other resources, it can maintain control of the resource.

3. Non-deprivation condition: Already allocated resources cannot be deprived by other threads and can only be released by themselves.

4. Loop, multiple threads form a cyclic waiting relationship

If the conditions are met at the same time, a deadlock may occur.

How to avoid deadlock?

1. Avoid using multiple locks

2. Set a timeout mechanism: Set a timeout when acquiring a lock. If the lock cannot be acquired within the specified time, give up and release the acquired lock. This avoids deadlocks caused by waiting too long.

3. Use ReentrantLock.tryLock() in try lock

4. Avoid nested locks

5. Use a fixed lock order: When multiple locks are unavoidable, ensure that threads acquire locks in the same order. This reduces the possibility of deadlock.

What is the difference between BIO NIO AIO?

BIO: Synchronous blocking. The caller waits for the request result to be returned.

NIO: synchronous and non-blocking. The caller does not have to wait for the result to be returned and can do other things.

AIO: Asynchronous non-blocking After initiating the call, the callee does not return a result. At this time, we can handle other requests. The callee usually relies on events, callbacks and other mechanisms to notify the caller of its return results.

What is the difference between GET and POST?

Get is unsafe because during the transmission process, the data is placed in the requested URL; the size of the transmitted data does not exceed 2k-4k

All Post operations are invisible to users. The POST method has no data size limit and can transmit data of any size.

The difference between HTTP and HTTPS

https: long connection

http: short connection

What is the difference between redirection and request forwarding in HTTP?

Forwarding: The getRequestDispatcher() method of request gets the ReuqestDispatcher object and calls

forward() method

Redirect: Call the sendRedirect() method of response

1> Redirect 2 requests and forward 1 request

2> The redirect address bar will change, but the forward address bar will remain unchanged.

3> Redirection is a browser jump, and forwarding is a server jump.

4> Redirection can jump to any URL, forwarding can only jump to the current project

5> Redirection will be lost, forwarding will not lose request data

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139,168 people are learning the system