Most of the problems are taken fromClick to open the linkI found some answers online and added some almost must-ask questions
one,Basics:
1) HashMap,LinkedHashMap,TreeMapThe difference
1. HashMap, LinkedHashMap, and TreeMap all belong to Map.
2. The main function of Map is to store key value pairs and get the value according to the key. Therefore, the key is not allowed to be repeated, but the value is allowed to be repeated.
3. HashMap is the most commonly used Map. It stores data according to the HashCode value of the key. It can directly obtain its value according to the key, with the fastest access speed. HashMap allows only one record to be Null; the value of multiple records to be Null; HashMap does not support thread synchronization, that is, multiple threads can write HashMap at any time; it may lead to inconsistency in data. If synchronization is required, you can use the synchronizedMap method of Collections to make HashMap synchronized.
4. LinkedHashMap is also a HashMap, but it maintains a two-way linked list internally, which can maintain order;
5. TreeMap can not only maintain order, but also be used for sorting;
2) ArrayListThe difference between LinkedList
1. ArrayList implements a data structure based on dynamic arrays, and LinkedList is a data structure based on linked lists.
2.
3.
3) An overview of how SpringMVC works
1. The client issues an HTTP request to the web server, and the web server parses the HTTP request. If it matches the request mapping path of the DispatcherServlet (specified in, or uses annotations), the web container forwards the request to the dispatcherServlet.
2. After receiving this request, the DispacherServelet finds the processor Haddler that handles the request based on the request information (including the URL, Http method, request header, request parameter cookie, etc.) and HandleMapping configuration.
3. The DispatcherServlet finds the corresponding Handler based on HandlerMapping, and handes the processing rights to the Handler (the Handler encapsulates the specific processing), and then the specific HandlerAdapter makes specific calls to the Handler.
4. After the Handler completes the data processing, it will return a ModelAndView() object to the DispatcherServlet.
5. The ModelAndView() returned by Handler is just a logical view, not a formal view. The DispatcherSevlet converts the logical view into a real view view through ViewResolver.
6. Dispatcher parses the parameters in ModelAndView() through model and parses it. Finally, it displays the complete view and returns it to the client.
4) Collection class: Comparison of List and Set
List is ordered (the order of storing elements is the same as the order of fetching elements), and Set is unordered; elements in the List collection have indexes, which can store duplicate data; Set cannot store duplicate data. Simply put, when the stored object has duplication, use List, and when there are no duplicate elements, use Set.
5) HashMapthe underlying implementation;
First, there is an array where each element is a linked list (maybe inaccurate expression). When adding an element (key-value), the hash value of the element key is calculated first to determine the position inserted into the array. However, elements with the same hash value may have been placed in the same position in the array. At this time, they are added to the back of elements with the same hash value. They are at the same position in the array, but they form a linked list. The hash values on the same linked list are the same, so the array stores the linked list. When the length of the linked list is too long, the linked list is converted into a red and black tree, which greatly improves the search efficiency.
6) How to implement HashMap sequential storage
There is a simulated "bidirectional loop link list" in LinkedHashMap to save the insertion order of entry. I can also use this method to save the order of key and value when inserting. The tentative name here is OrderedHashMap. The main code is copied from LinkedHashMap. It also maintains two simulated "bidirectional circular link lists": keyHeader and valueHeader, keeping the order of key or value from small to large. When an element put comes in, in addition to placing it in the hash bucket, it must also be inserted in the keyHeader according to the size of the key, and also in the valueHeader in the order of value. If you want to output, you can iterate forward or later to get the key or value ordered entry from these two "header pointers". (It can implement the output of key and value, positive order and reverse order, and only compare numerical types. If it is not numerical types, it will be processed normally like HashMap)
7) HashMapThe difference between HashTable and ConcurrentHashMap
A relatively simple answer to the difference between HashMap and HashTable is:
1. HashMap is non-thread-safe, and HashTable is thread-safe.The internal methods are basically donesynchronizedModification.
2. Due to synchronization, hash performance and other reasons, the performance is definitely better for HashMap.
3. HashMap allows null value to exist, and the key value put in HashTable only has a null,Throw it out directlyNullPointerException。
Comparison between HashMap and ConCurrentHashMap:
Let’s first introduce some of the ConcurrentHashMap, which is the thread-safe implementation of HashMap.
The synchronized keyword is used in HashTable. This is actually locking the object. The locking is the whole object. When the size of the Hashtable increases to a certain extent, the performance will drop sharply because it takes a long time to lock during iteration.
1. ConcurrentHashMap segments the entire bucket array (segment), and then uses lock locks to protect each segment. Compared with HashTable's syn keyword lock, the granularity is more refined and the concurrency performance is better. HashMap has no lock mechanism and is not thread-safe.
2. HashMap's key-value pairs are allowed to have null, but ConCurrentHashMap is not allowed.
8) String,StringBufferThe difference between StringBuilder
String string constant
StringBuffer String Variable (Thread Safe)
StringBuilder String Variable (non-thread safe)
9) waitThe difference between sleep
For the sleep() method, we must first know that the method belongs to the Thread class. The wait() method belongs to the Object class.
The sleep() method causes the program to pause the execution of the specified time and let go of the other thread of CPU, but its monitoring status remains, and will automatically resume the running status when the specified time is up.
During the call to the sleep() method, the thread will not release the object lock.
When the wait() method is called, the thread will give up the object lock and enter the waiting lock pool waiting for this object. Only after the notify() method is called for this object, the thread will enter the object lock pool and prepare to acquire the object lock and enter the running state.
10)JVMMemory structure, JVM algorithm
The JVM memory structure mainly has three major blocks: heap memory, method area and stack. Heap memory is the largest piece in the JVM consists of young generations and old generations, and the memory of young generations is divided into three parts: Eden space, From Survivor space, and To Survivor space. By default, young generations are allocated at a ratio of 8:1:1;
The method area stores class information, constants, static variables and other data. It is a thread-sharing area. It is distinguished from the Java heap. There is also an alias in the method area. The stack is also divided into a Java virtual machine stack and a local method stack. It is mainly used for the execution of methods.
11)What design patterns have been used? Write one by hand (except singleton);
Singleton mode
Implementation method:
a) Design the implemented class constructor as private.
b) Add static member variables of such references and instantiate them for them.
c) Provide the public CreateInstance function in the implemented class, and return the instantiated class, which is the static member variable in b.
Policy Mode
Implementation method:
a) Provide a public interface or abstract class to define the policy methods that need to be used. (Strategy abstract class)
b) Implementation class of policy abstract class for multiple implementations. (Strategy Implementation Class)
c) Environment class, encapsulation of multiple implementation classes, provides the number of members of interface types, which can be switched in the client.
d) Client calls environment class to switch between different policies.
Note:JdkIn-houseTreeSetand TreeMapThe sorting function is to use the policy mode.
Observer mode
The observer mode is the behavioral pattern of an object, also known as the publish-subscribe mode, the model-view mode, the source-listener mode or the slave mode.
Implementation method:
a) Role abstract class (provides add, delete and notification functions to observers).
b) Role concrete class, implement a, maintain a set of c (implementation of role abstract class).
c) Observer abstract class (method implemented after being notified by the role).
d) Observer implements class, implements c (multiple).
Note:JDKProvides support for observer mode, usingObservableClass andObserverinterface
Singleton pattern code
- public class Singleton {
- private Singleton(){}
- private static class SingletonBuild{
- private static Singleton value = new Singleton();
- }
- public Singleton getInstance(){ return ;}
- }
Factory mode code
- interface food{}
- class A implements food{}
- class B implements food{}
- class C implements food{}
- public class StaticFactory {
- private StaticFactory(){}
- public static food getA(){ return new A(); }
- public static food getB(){ return new B(); }
- public static food getC(){ return new C(); }
- }
- class Client{
- //The client code only needs to pass the corresponding parameters in to get the object
- //Users do not need to understand the logic inside the factory class.
- public void get(String name){
- food x = null ;
- if ( ("A")) {
- x = ();
- }else if ( ("B")){
- x = ();
- }else {
- x = ();
- }
- }
- }
12)SpringMVCWhat is the core of the request process and how to handle it;
What is the core of SpringMVC:
1. IoC: Control inversion
Concept: Control is transferred from the object itself to the container; the container creates instances based on the configuration file and creates dependencies between each instance.
Core: bean factory; in Spring, the various instances created by bean factory are called beans
2. AOP(Aspect-Oriented Programming): Oriented Programming
Concept: Simply put, AOP is that everyone performs their own duties and flexibly combines them to achieve a configurable, pluggable program structure.
From Spring's perspective, the biggest purpose of AOP is to provide transaction management capabilities. Transaction management is a focus. Your business is to access the database, and you don’t want to manage transactions (too annoying). Therefore, Spring will automatically start transactions before you access the database. After you access the database, it will automatically commit/roll back transactions for you.
How to handle the request process:
SpringMVC framework is a request-driven web framework, and uses the 'front-end controller' model to design, and then distributes it to the corresponding page controller for processing according to the 'request mapping rules'.
1. First, the user sends the request - >DispatcherServlet . After receiving the request, the distributor does not process it itself, but delegates it to other parsers for processing, as a unified access point, and performs global process control;
2. DispatcherServlet —>HandlerMapping , HandlerMapping will map the request to a HandlerExecutionChain object (including a Handler processor (Controller) object and multiple HandlerInterceptor interceptor) object. Through this policy pattern, it is easy to add a new mapping strategy;
3. DispatcherServlet —>HandlerAdapter , HandlerAdapter will package the processor as an adapter, thus supporting multiple types of processors, that is, the application of the adapter design pattern, so it is easy to support many types of processors;
4. HandlerAdapter ——> Calling the processor function processing method. HandlerAdapter will call the real processor's function processing method according to the adapted results to complete the function processing (the pre-interceptor of spring will be executed before calling the processor); and return a ModelAndView object (including model data and logical view name), and after returning to the view, the post-interceptor of spring will be executed;
5. The logical view name of ModelAndView - >ViewResolver. ViewResolver will resolve the logical view name into a specific View. Through this policy model, it is easy to replace other view technologies;
6. View ——> Rendering , View will render based on the Model model data passed in. The Model here is actually a Map data structure, so it is easy to support other view technologies (the interceptor after the process is performed in spring);
7. Return control to the DispatcherServlet, and the response is returned to the user by the DispatcherServlet, and the process ends.
13)springWhat is the principle of AOP in it
Spring implementation AOP: JDK dynamic proxy and CGLIB proxy JDK dynamic proxy: Its proxy object must be an implementation of a certain interface, which completes the proxy of the target object by creating an interface implementation class during runtime; the two core classes are InvocationHandler and Proxy. CGLIB proxy: The implementation principle is similar to the JDK dynamic proxy, except that the proxy object it generates during runtime is a subclass that extends to the target class. CGLIB is an efficient code generation package. The underlying layer is achieved by operating bytecode by ASM (open source java bytecode editorial library), with better performance than JDK; packages and packages need to be introduced. The bottom layer of the sections driven by AspectJ injection and @AspectJ annotation is actually implemented through dynamic proxy.
14)mybatisHow to handle the result set
After getting the result set, get the corresponding bean from the configuration file and reflect the
15)javaWhere does the polymorphism manifest in it?
Polymorphism: refers to the different states of the same thing, such as: water. Water can have three states:
Gas, liquids and solids. Then the polymorphism in JAVA can also be understood as this meaning:
The technique to set the parent object to be equal to one or more of its child objects,
For example Parent=Child;
Polymorphism enables the reference of objects of different classes using the same class (parent class),
And perform the same operation in different ways depending on the referenced object.
Polymorphic implementation includes two ways: overloading and overwriting
For example: Animal a = new Tiger(); This is an old topic, haha...
The parent class reference points to the child class object. The Animal class contains an eat() method, and the Tiger class inherits from
Animal class, if the subclass rewrites the eat() method of the parent class, then when called, you can follow the child class.
The form call of , is essentially the parent class method, but after the subclass is rewrite, it becomes another way.
This is polymorphism.
16)Talk about http, httpsprotocol;
The similarities between HTTP and HTTPS
In most cases, HTTP and HTTPS are the same because both use the same basic protocol, as HTTP or HTTPS client-browser, setting up a port to connect to the specified Web server. When the server receives the request, it returns a status code and a message, which may be a request message, or an error message indicating that an error is sent. The system uses a unified resource locator URI pattern, so resources can be uniquely specified. The only difference between HTTPS and HTTP is the description of a protocol header (https), and the others are the same.
The difference between HTTP and HTTPS
The URL of the HTTPS starts with http:// and the URL of the HTTPS starts with https://
It is not safe, and HTTPS is safe
The standard port is 80, while the standard port for HTTPS is 443
4. In the OSI network model, HTTP works at the application layer, while HTTPS works at the transport layer
No encryption is required, while HTTPS encrypts transmitted data
No certificate is required, while HTTPS requires a certificate
17)tcp/ipWhat does protocol cluster mean
TCP/IP is a network communication protocol group that contains many communication protocols. These protocols set standards for network devices, computers connected to the network, and how data is transmitted between them. The TCP protocol is also called the transmission control protocol, which acts on the transmission layer. IP protocol, also known as inter-network interconnection protocol, works at the network layer. They are all very important protocols in the TCP/IP protocol cluster.
18)osiLayer five network protocol;
OSI seven-layer model
Layer functions in OSI TCP/IP protocol family
Application layer file transfer, email, file service, virtual terminal TFTP, HTTP, SNMP, FTP, SMTP, DNS, Telnet
There is no protocol for data formatting, code conversion, and data encryption in the representation layer
There is no agreement on the session layer to undo or establish contact with other contacts
The transport layer provides end-to-end interfaces TCP, UDP
The network layer selects routing IP, ICMP, RIP, OSPF, BGP, IGMP for packets
The data link layer transmits frames with address and error detection functions SLIP, CSLIP, PPP, ARP, RARP, MTU
The physical layer transmits data on physical media in the form of binary data ISO2110, IEEE802, IEEE802.2
19)cookieand sessionThe difference is how to save user status in a distributed environment;
Cookie
In layman's terms, cookies are the information related to some websites stored locally after visiting certain websites, and reduce some steps when visiting them next time. Another more accurate statement is that cookies are small pieces of text stored by the server on the local machine and sent to the same server with each request. It is a solution to keep the state on the client side.
Session
Session is a HashTable structure used to store user data in a server.
the difference:
The most obvious difference is one on the client and one on the server. Because cookies exist on the client, users can see them, so they can also be edited and forged, which is not very safe.
When there are too many sessions, server resources will be consumed, so large websites will have special session servers, and cookies will have client, so there is no problem.
The support scope of the domain is different. For example, cookies can be used under the same level, while sessions cannot be used under the same level. The solution to this problem is JSONP or cross-domain resource sharing.
How to save user status in a distributed environment:
The first type: sticky session (Nginx)
Principle: Sticky Session refers to locking the user to a certain server. For example, in the example mentioned above, when the user requests for the first time, the load balancer forwards the user's request to the A server. If the load balancer sets up a sticky Session, then every request from the user will forward it to the A server, which is equivalent to sticking the user and the A server together. This is the sticky Session mechanism.
Advantages: Simple, no need to deal with the session.
Disadvantages: Lack of fault tolerance. If the currently accessed server fails and the user is transferred to the second server, his session information will be invalid.
Applicable scenarios: The failure has a small impact on the customer; the failure of the server is a low probability event.
Implementation method: Taking Nginx as an example, configuring the ip_hash attribute in the upstream module can achieve sticky Session.
upstream mycluster{
#Here are the two booted aboveTomcatserver
ip_hash;#viscositySession
server192.168.22.229:8080 weight=1;
server192.168.22.230:8080 weight=1;
}
The second type: session persists to the database
Principle: No need to say more, take out a database that is specially used to store session information. Ensure the session persistence.
Advantages: If there is a problem with the server, the session will not be lost.
Disadvantages: If the website has a large number of visits, storing the session in the database will put a lot of pressure on the database and additional overhead is required to maintain the database.
20)git, svn difference
same:
Able to record all changes to the file. This is for a large number of changes, but in the end I think the original version code is better. You can have records back to the past without using Copy old code to save as a file, and then find the history records you need from a large number of files at a certain time. Version control helps us store history records, which can easily query and roll back to a previous version.
different:
There are many differences between git and other version control systems (such as CVS). Git itself cares about whether the integrity of the file has changed, but most CV S or Subversion systems care about the differences in file content. Therefore, git is more like a file system, which directly obtains data on the local machine, and does not have to connect to the host side to obtain data.
git is a version control tool for Linux kernel development. Unlike centralized version control tools such as CVS and Subversion (SVN), it adopts the method of a distributed version library and can operate version control without server-side software, making the release and communication of source code extremely convenient. Git is fast, which is naturally important for big projects like the Linux kernel. What is best about git is its merge tracing capability.
SVN is a centralized or centralized version control system. The version library is centralized in the central server. When working, you use your own computer. Therefore, you must first get the latest version from the central server, and then do the work. After finishing, you need to push the work you have done to the central server. A centralized version control system must be connected to the Internet to work. If it is OK on a LAN, the bandwidth is large enough and the speed is fast enough. If it is on the Internet, if the Internet speed is slow, I will wonder.
Git is a distributed version control system, so it does not have a central server, and everyone's computer is a complete version library. In this way, there is no need to connect to the Internet when working, because the versions are all on their own computers. Since everyone’s computer has a complete version library, how can multiple people collaborate? For example, if you change file A on your computer, and others also change file A on your computer. At this time, you two only need to push their own modifications to each other and you can see each other's modifications.
21)Please write a piece of stack overflow and heap overflow code
- public class Test {
- //House
- public void testHeap(){
- for(;;){
- ArrayList list = new ArrayList (2000);
- }
- }
- //Stack
- int num=1;
- public void testStack(){
- num++;
- this.testStack();
- }
- public static void main(String[] args){
- Test t = new Test ();
- ();
- ();
- }
- }
22)Dynamic Proxy: The difference between JDK dynamic proxy and CGLIB proxy
When an object (client) cannot or does not want to directly refer to another object (target object), you can apply the proxy pattern to build a bridge between the two - the proxy object. According to the creation period of proxy objects, it can be divided into two types:
Static proxy: The programmer writes the proxy object class in advance, which already exists before the program is released;
Dynamic proxy: After the application is released, the proxy object is created dynamically.
Dynamic Agent
In this era, the agent object and the target object realize the same interface. The target object is an attribute of the proxy object. In the specific interface implementation, other business processing logic can be added before and after calling the corresponding method of the target object.
When using the proxy mode, you need to specify a specific target object. If you add a proxy class to each class, it will lead to many classes. At the same time, if you don’t know the specific class, how to implement the proxy mode? This leads to dynamic proxy.
JDK dynamic proxy can only generate proxy for classes that implement interfaces.
acting
The CGLIB (CODE GENERLIZE LIBRARY) agent is a class implementation agent, which mainly generates a subclass for the specified class, covering all methods in it, so the class or method cannot declare final.
If the target object does not implement an interface, the CGLIB proxy will be used by default;
If the target object implements an interface, you can force the proxy to be implemented using CGLIB (add the CGLIB library and add <aop:aspectj-autoproxy proxy-target-class="true"/> to the spring configuration).
AOP includes aspect, notification, and joinpoint. The implementation method is to add notifications to the target object's agent before and after the connection point to complete a unified facet operation.
22) The difference between forwarding and redirecting
Forwarding is server behavior, and redirection is client behavior.
two,IO:
1) bioThe difference between nio and aio
Synchronous blocking IO (JAVA BIO):
Synchronize and block. The server implementation mode is to connect to one thread. That is, when the client has a connection request, the server needs to start a thread for processing. If this connection does not do anything, it will cause unnecessary thread overhead. Of course, it can be improved through the thread pool mechanism.
Synchronous non-blocking IO (Java NIO):
Synchronous non-blocking, the server implementation mode is to request one thread, that is, the connection requests sent by the client will be registered with the multiplexer. The multiplexer polls the connection to an I/O request before starting a thread for processing. The user process also needs to ask whether the IO operation is ready from time to time, which requires the user process to constantly ask.
Asynchronous blocking IO (Java NIO):
In this way, after the application initiates an IO operation, it does not wait for the kernel's IO operation to complete, and will notify the application after the kernel completes the IO operation. This is actually the most critical difference between synchronization and asynchronous. Synchronization must wait or actively ask whether the IO is completed. So why is it blocked? Because it is done by select system calls at this time, and the implementation of the select function itself is blocking, and one advantage of using select function is that it can listen to multiple file handles at the same time (if from the perspective of UNP, select is a synchronous operation. Because after select, the process also needs to read and write data), thereby improving the concurrency of the system!
(Java AIO(NIO.2)) Asynchronous non-blocking IO:
In this mode, the user process only needs to initiate an IO operation and return immediately. After the IO operation is truly completed, the application will be notified that the IO operation is completed. At this time, the user process only needs to process the data and does not need to perform actual IO read and write operations, because the real IO read or write operations have been completed by the kernel.
2) Core components Buffer, Channel, Selector, etc., what are their uses
Buffer
Essence: A piece of memory that can write data or read data from it. This piece of memory is wrapped into an NIO buffer object and provides relevant access for access
Channel
Similar to streams, but somewhat different:
1. You can read data from the channel and write data to the channel. But the reading and writing of streams are usually one-way.
2. The channel can be read and written asynchronously.
3. The data in the channel must always be read to a buffer first, or it must always be written to a buffer.
Seletor
Selector is a component in Java NIO that can detect one or more NIO channels and know whether the channel is ready for a read and write event. In this way, a single thread can manage multiple channels, thereby managing multiple network connections.
3) NIOWhat's the point of comparison with IO
The first biggest difference between Java NIO and IO is that IO is stream-oriented and NIO is buffer-oriented.
1. io is stream-oriented, that is, when reading data, it is read one by one from the stream, so the data cannot be considered as a whole and there is no buffer; nio is buffer-oriented, the data is stored in the buffer, and the reading of the data is performed in the buffer, so data offset operation is more convenient.
2. io is blocking. When a thread operates io, if there is no data to be read at present, then the thread is blocked. Since nio operates io on the channel, it is not blocked. When a channel has no data to be read, the channel can be switched to process other ios.
3. Nio has a selecter selector, which means that threads can select multiple channels through the selector, while io can only handle one.
4) Which open source projects use NIO
dubboNetty in it uses a lot of nio
5) nioFramework: The implementation principle of dubbo
As the rpc framework, the effect of dubbo is to call remote methods just like locally. How to do it? There is a description of remote methods locally, including method names, parameters, and return values. In dubbo, the same interface is used remotely and locally; then, there is a package for network communication, and the communication details are completely invisible to the caller. What network communication needs to do is to pass the attributes of the calling method to the server through a certain protocol (simply, the message format); the server parses the call information according to the protocol; executes the corresponding method; passes the return value of the method to the client through the protocol; the client parses it again; in terms of calling methods, it can be divided into synchronous calls and asynchronous calls; simply put, it is basically this process.
three,algorithm
1) Bubble sort
Principle: Taking sorting from small to large as an example, each round of sorting finds the maximum value in the unsorted sequence and puts it at the end.
Suppose the length of the array is N:
(1) Compare the two adjacent data in front and back. If the previous data is greater than the subsequent data, exchange the two data.
(2) After traversing the 0th data of the array to N-1 data once, the largest data will be "sinked" to the N-1th position of the array.
(3) N=N-1. If N is not 0, repeat the previous two steps, otherwise the sorting will be completed.
The above is the basic idea of bubble sorting. According to this definition, you can write code quickly:
- /**
- * The first implementation of bubble sorting, without any optimization
- * @param a
- * @param n
- */
- public static void bubbleSort1(int [] a, int n){
- int i, j;
- for(i=0; i<n; i++){//Denote n-order sorting process.
- for(j=1; j<n-i; j++){
- if(a[j-1] > a[j]){//If the number in the front is greater than the number in the next, then the number in the next is exchanged
- //Exchange a[j-1] and a[j]
- int temp;
- temp = a[j-1];
- a[j-1] = a[j];
- a[j]=temp;
- }
- }
- }
- }// end
2) Quick sort
Quick sorting is an upgrade of bubble sorting. They all belong to swap sorting, and they all use constant comparison and movement to achieve sorting. Quick sorting is a very efficient sorting algorithm. Its implementation increases the distance between the comparison and movement of records, and moves records with larger keywords directly from the front to the back, and records with smaller keywords directly from the back to the front, thereby reducing the total number of comparisons and movements. At the same time, the idea of "dividing and conquering" is adopted to split the big into small, and the small into smaller ones. The principle is as follows: For a given set of records, select a benchmark element, usually the first element or the last element is selected, and through a scan, the sequence to be sorted is divided into two parts, part smaller than the benchmark element, and part greater than or equal to the benchmark element. At this time, the benchmark element is in the correct position after it is sorted, and then the two parts are recursively sorted in the same way until all records in the sequence are ordered.
Javaaccomplish:
- publicclass QuickSort {
- publicstaticvoidsort(int a[], int low, int hight) {
- int i, j, index;
- if (low > hight) {
- return;
- }
- i =low;
- j =hight;
- index = a[i]; // Use the first record of the subtable as the benchmark
- while (i < j) { // Scan the middle alternately from both ends of the table
- while (i < j && a[j] >= index)
- j--;
- if (i < j)
- a[i++] = a[j];// Replace low-bit records with records smaller than the benchmark
- while (i < j && a[i] < index)
- i++;
- if (i < j) // Replace high-level records with records larger than the benchmark
- a[j--] = a[i];
- }
- a[i] = index;// Replace the reference value back a[i]
- sort(a, low, i - 1); // Recursively sort the low subtable
- sort(a, i + 1, hight); // Recursively sort the high subtable
- }
- publicstaticvoidquickSort(int a[]) {
- sort(a, 0, - 1);
- }
- publicstaticvoidmain(String[] args) {
- int a[] = { 49, 38, 65, 97, 76, 13, 27, 49 };
- quickSort(a);
- ((a));
- }
- }
3) Binary search
Two-part search is also called half-part search (BinarySearch), it is a more efficient search method. However, half-finding requires that linear tables must adopt sequential storage structures, and the elements in the table are arranged in an orderly manner by keywords.
First, assume that the elements in the table are arranged in ascending order and record the middle position of the table.KeywordsCompared with the search keyword, if the two are equal, the search will be successful; otherwise, use the intermediate positionRecordDivide the table into two sub-tables. If the keywords recorded in the middle position are greater than the search keyword, further search the previous sub-table, otherwise further search the next sub-table. Repeat the above process until you find a satisfying condition.Record, make the search successful, or until the child table does not exist, and the search is unsuccessful.
Javaaccomplish:
Four,Multi-threaded related
1) Implementation of blocking queues Refer to the underlying implementation of ArrayBlockingQueue
ArrayBlockingQueue: A blocking queue based on an array implementation. The capacity size must be formulated when creating an ArrayBlockingQueue object. And fairness and inequity can be specified, which is not fair by default, that is, the queue with the longest waiting time is not guaranteed to be accessed first.
LinkedBlockingQueue: A blocking queue based on linked list implementation. If the capacity size is not specified when creating a LinkedBlockingQueue object, the default size is Integer.MAX_VALUE.
ArrayBlockingQueue is based on an array blocking queue implementation. In ArrayBlockingQueue, a fixed-length array is maintained to cache data objects in the queue. This is a commonly used blocking queue. In addition to a fixed-length array, there are also two shaping variables stored inside ArrayBlockingQueue, which identifies the position of the head and tail of the queue in the array. ArrayBlockingQueue shares the same lock object when the producer puts data and the consumer obtains data, which also means that the two cannot truly run in parallel, which is especially different from LinkedBlockingQueue; according to the implementation principle, ArrayBlockingQueue can completely use separate locks, thereby achieving complete parallel operation of producer and consumer operations. Doug Lea didn't do this, perhaps because the data write and fetch operations of ArrayBlockingQueue are light enough that the introduction of an independent lock mechanism is not cheap at all in performance, except for the additional complexity to the code. There is also a clear difference between ArrayBlockingQueue and LinkedBlockingQueue in that the former does not generate or destroy any additional object instances when inserting or deleting elements, while the latter generates an additional Node object. In systems that require efficient and concurrent processing of large batches of data over a long period of time, there are still some differences in their impact on GC. When creating an ArrayBlockingQueue, we can also control whether the object's internal lock adopts a fair lock, and the default is to use a non-fair lock.
2) Why use thread pool
Thread execution process:
Create (t1) Run (t2) Destroy (t3)
Total time of thread running T= t1+t2+t3;
If some business logic requires frequent threads to perform some simple tasks, a lot of time will be wasted on t1 and t3.
To avoid this problem, JAVA provides thread pool
Threads in the thread pool can be reused and will not be destroyed after the thread runs the task.
Because creating threads is expensive, when your program needs to frequently create and destroy some of the same threads, you can first create a certain number of threads to let them sleep. When you need a thread, take one out of it and put it back after running, which increases efficiency
3) volatileHow to use keywords
Make variables visible in multithreads
4) Methods of process communication
Message queue, shared memory, semaphore, socket communication, etc.
five,Database related
1) msyqlOptimization experience
1. Optimize query for query cache
2. Create an index for the search field
3. Set an ID for each table
4. Use ENUM instead of VARCHAR
5. Vertical splitting of table
Solve the problem of too many table fields
Split principle:
Put uncommon fields in a table
Put large fields in a table independently
Put frequently used fields together
6. Horizontal splitting of tables
To solve the problem of table data volume, the table structure after splitting is the same.
Existing problems: cross-partition table query, statistics and background report operations
2) mysqlStatement optimization
1. Try to avoid operations on columns, as this will cause index failure
2. When using JOIN, you should use a small result set to drive the large result set, and at the same time split the complex JOIN query into multiple queries, because multiple JOIN tables may lead to more locking and blockages.
3. use LIKE Avoid using %%
4. select Specify query fields, do not find them all, save memory
5. Save interaction using batch insert statement
6. limitWhen the cardinality of the relatively large, use between,between Limited ratio limit Fast, butbetweenThere are also defects, ifidThere is a break in the middle or a middle partidIf you don't read, there will be less data
7. Do not use rand Function takes multiple random records
8. Avoid using NULL
9.
Do not use count(id)
, It should be count(*)
10. Don’t do unnecessary sorting operations, but sort them in the index as much as possible.
3) Talk about the characteristics and isolation levels of transactions
Isolation level:
1. Dirty Reading
Dirty reading refers to the reading of data from another uncommitted transaction in one transaction process.
When a transaction is modifying a certain data multiple times, and the multiple modifications in this transaction have not been submitted, then a concurrent transaction accesses the data, resulting in inconsistent data obtained by the two transactions. For example: User A transfers 100 yuan to User B, and the corresponding SQL command is as follows
update account set money=money+100 where name=’B’; (A notifies B at this time)
update account set money=money - 100 where name=’A’;
When only the first SQL is executed, A notifies B to view the account, and B finds that the money has indeed arrived (dirty reading occurs at this time). After that, no matter whether the second SQL is executed or not, as long as the transaction is not submitted, all operations will be rolled back. Then when B checks the account again, you will find that the money has not actually been transferred.
2.
A non-repeatable read refers to a transaction-wide query that returns different data values for a certain data in the database, because it is modified and submitted by another transaction during the query interval.
For example, transaction T1 is reading a certain data, and transaction T2 immediately modifys this data and submits a transaction to the database. Transaction T1 reads the data again and gets different results and sends non-repeatable reads.
The difference between non-repeatable reading and dirty reading is that a transaction reads dirty data that is not committed by another transaction, while non-repeatable reading reads data that was committed by the previous transaction.
In some cases, non-repeatable reading is not a problem. For example, if we query a certain data multiple times, of course, the result obtained by the last query is mainly based on the results obtained. But in other cases, problems may occur, for example, the same data may be queried in sequence, and the same data may be different.
3. Virtual Reading (Illusion Reading)
Fantasy reading is a phenomenon that occurs when a transaction is executed independently. For example, transaction T1 modifies a data item from "1" to "2" on all rows in a table. At this time, transaction T2 inserts a row of data items into the table, and the value of this data item is still "1" and submitted to the database. If the user who operates transaction T1 checks the data just modified, he will find that there is still a line that has not been modified. In fact, this line was added from transaction T2, as if an illusion was created. This is the illusion reading.
Both the illusion and non-repeatable read reads another transaction that has been submitted (this is different from dirty reading). The difference is that the illusion and non-repeatable read query are both the same data item, while the illusion is aimed at a whole batch of data (such as the number of data).
The MySQL database provides us with four isolation levels:
1) Serializable: It can avoid dirty reading, non-repeatable reading, or phantom reading.
2) Repeatable read: It can avoid dirty reading and non-repeatable reading.
3) Read committed (read submitted): can avoid dirty reading.
4) Read uncommitted (read not submitted): The lowest level, no situation can be guaranteed.
4) How to achieve the difference between pessimistic lock and optimistic lock
1. Pessimistic lock: that is, it is very pessimistic. Every time you take the data, you feel that the data will be changed, so when you take the data, lock the record, so that others can't change the data until your lock is released.
2. Optimistic lock: that is, it is very optimistic. When querying data, you always feel that no one will change the data. When it is updated, you will judge whether the data has been changed. If someone changes it, the update will fail.
A typical pessimistic lock call that depends on a database:
select * from account where name=”rica” forupdate
Pessimistic locking is also implemented based on the database locking mechanism.
Optimistic locks are mostly implemented based on the data version (Version) recording mechanism. They need to add a version identifier to each row of data (that is, each row of data has one more field version). Each time the data is updated, the corresponding version number must be updated +1.
The working principle of optimistic locking: When reading out the data, read out this version number together, and when updated later, add one to this version number. At this time, the version data of the submitted data is compared with the current version information recorded in the database table. If the submitted data version number is greater than the current version number of the database table, it will be updated, otherwise it will be considered expired data.
Optimistic locks can also be based on timestamp, ALL, etc.;
all means that all fields of the record are version control information. When updating, all data before the update is used as a WHERE condition.
timestamp is to compare the time when querying as the conditions when updating with the database record whether it is equal.
select * from users whereuserName='fudong';
update users set userSex='female',updateDate=sysDate where userName='fudong' and updateDate=oldDate;
5) What problems will optimistic locks cause
ABA Questions
Optimistic locks only compare the original data when submitted
However, if a problem occurs between A-B-A during this period, optimistic locking will think that the data is normal
The solution to this problem is to add the version number and then make a comparison when submitting
six,nosqlRelated (mainly redis)
1) redisThe difference between memcache
1. In Redis, not all data is always stored in memory, which is the biggest difference compared to Memcached.
2. Redis not only supports simple k/v type data, but also provides storage of data structures such as list, set, and hash.
3. Redis supports data backup, that is, data backup in master-slave mode.
4. Redis supports persistence of data, which can keep the data in memory on disk and can be loaded again for use during restart.
2) redisHow to persist: rdb and aof
RDB persistence can generate point-in-time snapshots of datasets within a specified time interval
Advantages
RDB files are smaller than AOF
RDB performs better
Disadvantages
RDB is not persistent enough
If the file is too large during RDB persistence, the server may block, stop client requests.
AOF redis will append each received write command to the file through the write function (default is).
Advantages
AOF has more durability (can be saved once per second or per operation)
The AOF file orderly saves all write operations performed on the database. These write operations are saved in the format of the Redis protocol, so the content of the AOF file is very easy to understand and parse the file.
AOF is an incremental operation
Disadvantages
For the same dataset, the volume of the AOF file is usually greater than the volume of the RDB file.
Depending on the fsync strategy used, AOF may be slower than RDB.
When Redis is started, if both RDB persistence and AOF persistence are turned on, the program will prioritize the AOF file to restore the dataset, because the data saved by the AOF file is usually
seven,linuxRelated
1) linuxWhat are the commonly used commands
1.
2.
3.
4.
5.
6.
7. rm command
8.
9.
10. tar command
11. cat command
12. chmod command
2) How to get the pid of a java process
ps -ef | grep java
kill -9 XXXXX XXXXXThe serial number found for the above
3) How to print logs in real time
cat /var/log/*.log
If the log is being updated, how to view tail -f /var/log/messages in real time
You can also use watch -d -n 1 cat /var/log/messages
-d means highlighting different places, and -n means how many seconds to refresh.