Part I JAVA
1, JVM
-
Let's talk about the memory model of the JVM before and after 1.8?
Why do I need a program counter?
1.JVM Memory model refers to JVM Memory area partition 2.JVM1.8 Modification of: -Modified content: the method area is removed and the metadata area is added. Moreover, the metadata area is in local memory and is no longer limited to JVM The size of memory is related to the machine memory. -Reason for modification: as today's frameworks and programs contain many dependencies, and many class objects of these dependencies are stored in the permanent generation, this part of the content tends to overflow memory, so simply put this part of the content into heap memory or local memory for storage. -Meta space has the following characteristics: a.Each loader has a dedicated storage space. b.A class will not be recycled separately. c.The position of objects in meta space is fixed. d.If it is found that a loader is no longer alive, the relevant space will be recycled. 3.The program counter records the address or line number of the bytecode being executed by the current thread. JVM There is thread switching in, which is mainly used to ensure multi threading JVM Normal execution of the program.
-
JVM tuning
How do I resize the heap? Which parameter do you want to modify?
1.Heap size setting: -Xms Initial heap size,
-
Let's talk about the execution process of Java methods in more detail. Compilation, loading (class loading), execution and interpretation
1. Load: generate a file representing this class in memory java.lang.Class Object as the entry of various data of this class in the method area 2. Verification: ensure Class Whether the information contained in the byte stream of the file meets the requirements of the current virtual machine 3. Preparation: formally allocate memory for class variables (static variables) and set the initial value stage of class variables, that is, allocate the memory space used by these variables in the method area 4. Resolution: the process by which a virtual machine replaces a symbolic reference in a constant pool with a direct reference - Symbol reference: the target of the reference does not have to be loaded into memory - Direct reference: the target of the reference must already exist in memory 5. Initialization: executes the defined in the class Java Program code - Execution class constructor<client>method - <client>The method is formed by the combination of the assignment operation of the class variables in the compiler and the statements in the static statement block
-
New Java 8 features
1. Lambda expression: Lambda Allows functions to be passed as arguments to a method (functions are passed as arguments to methods) 2. Functional interface: refers to an interface that has only one abstract method, but can have multiple non abstract methods. Such an interface can be implicitly converted to Lambda expression 3. Method reference: method reference provides a very useful syntax, which can directly reference existing methods Java The method or constructor of a class or object (instance) lambda In combination, method reference can make the language structure more compact and concise and reduce redundant code 4. Default method: the default method is a method with an implementation in the interface 5. **Stream API**: Newly added Stream API(java.util.stream) Introducing a true functional programming style to Java Yes. 6. Optional Class: Optional Class has become Java 8 Part of the class library used to solve null pointer exceptions. 7. Date Time API: Strengthen the processing of date and time. 8. Nashorn, JavaScript Engine: Java 8 Provides a new Nashorn javascript Engine, it allows us to JVM Run specific on javascript application
-
String s = new String("abc"); What is stored in memory after the code runs? Where is the variable s?
String str = new String("abc"); String str = "abc"; /* The first is to create objects with new(), which will be stored in the heap, and a new object will be created every time it is called; The second is to create an object reference variable str of String class in the stack, and then find out whether "abc" is stored in the stack. If not, store "abc" in the stack and make str point to "abc". If "abc" already exists, directly make str point to "abc". When comparing whether the values in the class are equal, use the equals() method; When testing whether the references of two wrapper classes point to the same object, use== */
-
What are the possible causes of memory overflow?
Under what circumstances does the stack overflow memory?
Java virtual machine stack under what circumstances does the depth of the thread request stack exceed the maximum depth of the current Java virtual machine stack? What typical scenario would this happen?
1.out of memory out of memory: It means that the program does not have enough memory space for its use when applying for memory out of memory;For example, I applied for one integer,But I saved it long To save, that is, memory overflow. 2.Memory leak memory leak: It means that the program cannot release the applied memory space after applying for memory. The harm of a memory leak can be ignored, but the consequences of memory leak accumulation are very serious, no matter how much memory,It will be taken up sooner or later. 3.Memory leak types: frequent memory leak, accidental memory leak, one-time memory leak and implicit memory leak -Frequent memory leaks. The code with memory leak will be executed many times, and each time it is executed, it will lead to a memory leak. -Accidental memory leak. The code with memory leakage will only occur in some specific environment or operation process. Recurrent and sporadic are relative. For a specific environment, occasional may become frequent. Therefore, the test environment and test methods are very important to detect memory leaks. -One time memory leak. The code with memory leakage will be executed only once, or there will always be one block and one block of memory leakage due to algorithmic defects. For example, memory is allocated in the constructor of a class, but it is not released in the destructor, so memory leakage will only occur once. -Implicit memory leak. The program allocates memory continuously during operation, but does not release memory until the end. Strictly speaking, there was no memory leak because the final program released all the requested memory. However, a server program needs to run for several days, weeks or even months. Failure to release memory in time may eventually lead to the depletion of all memory in the system. Therefore, we call this kind of memory leak implicit memory leak. 4.Memory overflow reason: -The amount of data loaded in memory is too large, such as fetching too much data from the database at one time; -There is a reference to the object in the collection class, which is not cleared after use JVM Cannot recycle; -There is an endless loop in the code or the loop produces too many duplicate object entities; -In the third-party software used BUG; -The memory value of startup parameter is set too small 5.Memory overflow solution -The first step is to modify JVM Start parameters to directly increase memory. -Step 2: check the error log and view"OutOfMemory"Whether there are other exceptions or errors before the error. -The third step is to arrange experienced programmers to walk through and analyze the code to find out the location where memory overflow may occur. -Step 4: use the memory view tool to dynamically view the memory usage. 6.Memory leak reason: -A situation such as C/C++ In language, the allocated memory in the heap. When it is not released, all ways that can access this memory are deleted (such as pointer re assignment) -In another case, when the memory object is no longer needed, it still retains the memory and its access method (Reference) -In the first case, in Java It has been well solved due to the introduction of garbage collection mechanism. So, Java Memory leakage in mainly refers to the second case.
-
What kind of objects cannot be recycled? What method is used to determine whether objects can be recycled? What objects can be used as GC roots?
What are the garbage collection algorithms? The "copy" algorithm wastes half the space. Why use this algorithm? What are the advantages and disadvantages of mark clear and mark tidy?
What are the garbage collectors? CMS and G1 garbage collection process? Which stage in CMS will stop the world? What kind of garbage collection algorithm does CSM use? Which garbage collection algorithm is used in G1? Why should CMS use mark clear instead of mark tidy algorithm?
How does garbage collection solve the problem of cross generational reference?
1. Algorithm for determining garbage -Reference counting: references are associated with objects. If you want to manipulate an object, you must use a reference. If the object has no reference associated with it, it can be recycled -Reachability analysis: solve the circular reference problem of reference counting method; If in“ GC roots"If there is no reachable path between and an object, the object is said to be unreachable; It takes at least two marking processes for an unreachable object to become a recyclable object 2. GC roots -VM Stack (Local variable table in stack frame)Referenced objects in -The object referenced by the class static property in the method area -The object referenced by the constant in the method area -Local method stack JNI(Native Method) 3.Garbage collection algorithm: mark removal algorithm( Mark-Sweep),Replication algorithm( copying),Label sorting algorithm(Mark-Compact),Generational collection algorithm 4."The "copy" algorithm wastes half the space, but it can solve the problem of memory fragmentation 5.Garbage collector: Serial,ParNew,Parallel Scavenge,Serial Old,Parallel Old,CMS,G1
-
Parental delegation model? What mechanism can break the parental delegation model? Class loader type?
1.Concept: when a class receives a class loading request, it will not try to load the class by itself, but delegate the request to the parent class to complete it. Only when the parent class loader feeds back that it cannot complete the request, the child class loader will try to load it by itself 2.Break: - rewrite loadClass(): The parental delegation mechanism is implemented through this method. Rewriting the loading rules is equivalent to breaking the mechanism, and the user-defined loading delegation mechanism can be realized - Using thread context class loader: the basic class calls back to the user code - Hot code replacement (pursuit of dynamics) 3.Class loader: startup class loader, extension class loader and application class loader(Application ClassLoader),By inheritance java.lang.ClassLoader Implement a custom class loader.
2, JAVA collection
-
Let's talk about the difference between ArrayList and LinkList: the difference between array and linked list - find, modify and insert
-
HashMap capacity expansion mechanism, why does HashMap generally initialize a size when it is defined? The underlying principle of HashMap? Is HashMap thread safe? Why is the capacity expansion factor of HashMap in Java 0.75? The underlying data structure of HashMap?
1.Capacity expansion mechanism: use an array with larger capacity to replace the existing array with smaller capacity, transfer()Method the original Entry Copy the elements of the array to the new Entry Array. Expand to the next exponential power of 2 2.Why build hashmap Initialization size is required: if we do not set the initial capacity size, as the element increases, HashMap There will be multiple capacity expansion, and HashMap The capacity expansion mechanism in determines that each capacity expansion needs to be rebuilt hash Table, which has a great impact on performance. 3.Thread unsafe 4.The tradeoff between improving space utilization and reducing query cost is mainly Poisson distribution, 0.75 If the collision is minimal, a compromise is sought on the cost of time and space -The loading factor is too high, for example, 1, which reduces the space overhead and improves the space utilization, but also increases the query time cost; -Load factor too low, e.g. 0.5,Although the query time cost can be reduced, the space utilization is very low and the query efficiency is improved rehash Number of operations. 5.Underlying data structure: array+Linked list+Red black tree( JDK1.8 Red and black trees added)
-
Talk about ConcurrentHashMap? What is the difference between HashMap and concurrent HashMap? How does the underlying layer of ConcurrentHashMap achieve security? The get operation in ConcurrentHashMap does not need to be locked in 1.7 and 1.8?
1.Difference: is the thread safe 2.Security implementation: 1.7(ReentrantLock+Segment),1.8(synchronized+CAS) 3.get There is no need to lock the whole operation because Node Members of val Yes volatile Decorated. And arrays volatile It doesn't matter,Array use volatile Modification is mainly to ensure the visibility when the array is expanded.
-
How is LinkedHashmap implemented
1.Through hash table and linked list 2.LinkedHashMap Realized Map Interface, inherited from HashMap,And HashMap The difference is that it maintains a double linked list, which can ensure the order of iteration.
-
What are commonly used in Java collections? Under what scenarios are they generally used?
It is mainly selected according to the characteristics of the set. For example, it is selected when we need to obtain the element value according to the key value Map The collection under the interface, which is selected when sorting is required TreeMap,Select when sorting is not required HashMap,If you need to ensure thread safety, choose ConcurrentHashMap.When we only need to store element values, we choose to implement Collection The collection of interfaces. Select the implementation when it is necessary to ensure that the elements are unique Set A collection of interfaces, such as TreeSet or HashSet,No need to choose to implement List Interface, such as ArrayList or LinkedList,Then it is selected according to the characteristics of the set that implements these interfaces.
-
What other interfaces are there under the Collection of Java? What are the Map collections?
1.List,Set 2.quite a lot
-
What is the difference between list and set? How does set ensure that elements cannot be repeated?
1.say something List,Set,Map The difference between the three? -List(A good helper in dealing with order): List The interface stores a set of non unique (multiple elements can reference the same object) and ordered objects -Set(Focus on unique nature): Duplicate collections are not allowed. No more than one element references the same object. -Map(use Key Experts to search): Use key value pair storage. Map Maintenance and Key Has an associated value. Two Key You can reference the same object, but Key Can't repeat, typical Key yes String Type, but it can also be any object. 2.Guaranteed non repeatable-(hashCode and equals) -On the way Set When you add an object to a collection, you first pass the hashCode Method to calculate the of the object hash Value. -Will be calculated hash Value go hash Query in table, if hash If the value does not exist in the table, the object is added successfully. -If hash There is this in the table hash Value, the object to be added will be further compared with the object in the collection, and the equals Method to compare objects field. -If field Similarly, it is a duplicate object, and the object addition fails. -If equals Returned is false,It means that the two objects are not the same object. The object will be added to the end of the existing object list. This situation is called hash Collision.
3, JAVA threading and multithreading
-
Let's talk about the six states and transitions of threads in Java, and how to create threads?
1. **initial(NEW)**: A new thread object has been created, but it has not been called start()method. 2. **function(RUNNABLE)**: Java The thread will be ready( ready)And in operation( running)The two states are generally called "running". After the thread object is created, other threads(such as main Thread) called the of the object start()method. The thread in this state is located in the runnable thread pool and waits to be selected by thread scheduling to obtain CPU The right to use is now ready( ready). Thread in ready state is getting CPU After the time slice, it becomes running( running). 3. **block(BLOCKED)**: Indicates that the thread is blocking a lock. 4. **wait for(WAITING)**: The thread entering this state needs to wait for other threads to make some specific actions (notifications or interrupts). 5. **Timeout wait(TIMED_WAITING)**: This state is different from WAITING,It can return by itself after a specified time. 6. **termination(TERMINATED)**: Indicates that the thread has completed execution.
-
Let's talk about thread safety, concept and implementation in Java. Write a case of two thread deadlock, or describe it
How to ensure thread safety? What is the difference between these ways of ensuring thread safety?
1.If there are multiple threads running in the process where the code is located, these threads may run the code at the same time. If the result of each run is the same as that of a single thread, and the values of other variables are the same as expected, it is thread safe. 2.Mutually exclusive synchronization, non blocking synchronization and non synchronization schemes
-
What is the role of volatile keyword?
In what scenarios will volatile be used? Take a real scene?
The underlying implementation of volatile, how to prevent instruction rearrangement threads, what states are there, and how to transfer between these states.
Why is the value of volatile accessed by the thread the value in main memory?
1.Solve the problem of thread concurrency 2.1)The write operation on the variable does not depend on the current value 2) the variable is not contained in an invariant with other variables
-
Has the thread pool been used? Let's talk about four common thread pools.
How do you implement a class that allows you to implement a thread pool with caching?
What are the rejection policies for thread pools?
1.Four common thread pools - CachedThreadPool: Create a thread pool where you can create new threads as needed - FixedThreadPool: Create a reusable thread pool with a fixed number of threads to run these threads in a shared unbounded queue - ScheduledThreadPool: Create a thread pool that can schedule commands to run after a given delay or execute periodically - SingleThreadExecutor: Returns a thread pool (this thread pool has only one thread),This thread pool can restart a thread after the thread dies (or when an exception occurs) to continue executing instead of the original thread 2.Reject policy for thread pool:CallerRunsPolicy\AbortPolicy\DiscardPolicy\DiscardOldestPolicy
-
What's the difference between sleep and wait?
What is the difference between the run() and start() methods?
1. yes sleep()Method belongs to Thread Class. and wait()Method belongs to Object Class 2. sleep()Method causes the program to suspend execution for the specified time cpu The other thread, but its monitoring status remains the holder. When the specified time is up, it will automatically return to the running state. 3. In call sleep()Method, the thread does not release the object lock. 4. And when called wait()Method, the thread will give up the object lock and enter the waiting lock pool waiting for this object. Only this object can be called notify()Method before the thread enters the object lock pool to obtain the object lock and enter the running state. 1. start()Method to start the thread, which really realizes multithreading. There is no need to wait run After the method body code is executed, you can directly continue to execute the following code. 2. By calling Thread Class start()Method to start a thread that is ready and not running. 3. method run()It is called the thread body, which contains the content of the thread to be executed. The thread enters the running state and starts running run Function. Run Method ends and this thread terminates. then CPU Schedule other threads.
-
Have Callable() and Future() been used?
What are the advantages of using Callable() to create threads over the other two methods?
1.Create a thread with a return value 2.You can also inherit other classes, and multiple threads can share the same class target Object, which is suitable for multithreading to access the same resource cpu Separate from the data to form a clear model, which better reflects the object-oriented idea and return value
-
volatile int a=1. Write a method to accumulate A. This method is accessed by multiple threads. Can this implementation ensure thread safety?
In detail, why can't two threads access at the same time ensure thread safety? (if thread safe a should be 3, but thread unsafe, it won't be 3)
-
There is a file that many people are reading. Concurrent reading has no impact, but when a person is writing a file, other people are not allowed to write. If he is already writing the file, it is not allowed to read, because what he reads during the modification process is not the latest. If someone reads, he does not want someone to write. If this function is to be realized, how should the code be implemented and multi-threaded control be done?
-
new where is a thread?
first java Objects in are usually in heap memory(If JIT After compilation optimization, objects may be allocated on the stack through escape analysis),therefore java in Thread The object itself must also be in heap memory,Only when called start()Method is called native method start0(),This method is used to create the corresponding operating system os thread(And java thread 1 Pair 1 Relationship),The thread stack space it opens does not belong to jvm Managed heap memory space.
-
What is the difference between the volatile and synchronized keywords in Java? Usage scenarios?
The difference between synchronized and ReentrantLock
1.difference: -volatile Keyword is a lightweight implementation of thread synchronization, so volatile Performance ratio synchronized Keywords are better. however volatile Keywords can only be used for variables, not synchronized Keywords can modify methods and code blocks. synchronized Keywords in JavaSE1.6 After that, it mainly includes the bias lock, lightweight lock and other optimizations introduced to reduce the performance consumption caused by obtaining and releasing locks. After that, the execution efficiency has been significantly improved and used in practical development synchronized There are more keyword scenarios. -Multithreaded access volatile Keywords are not blocked, and synchronized Keywords may be blocked -volatile Keywords can ensure the visibility of data, but can not guarantee the atomicity of data. synchronized Keywords both can be guaranteed. -volatile Keyword is mainly used to solve the visibility of variables between multiple threads, and synchronized Keyword solves the synchronization of accessing resources between multiple threads. 2.Similarities and differences: -Both are reentrant locks: the concept of "reentrant lock" is that you can obtain your own internal lock again -synchronized Depend on JVM and ReentrantLock Depend on API -ReentrantLock than synchronized Some advanced features have been added:①Waiting can be interrupted;②Fair lock can be realized;③Selective notification can be realized (lock can bind multiple conditions)
-
What is the difference between processes and threads?
1.difference: -Scheduling: thread is the basic unit of scheduling and allocation, and process is the basic unit of owning resources -Concurrency: not only processes can execute concurrently, but also multiple threads of the same process can execute concurrently -Owning resources: a process is an independent unit that owns resources. Threads do not own system resources, but can access resources belonging to the process. -System overhead: when creating or undoing a process, because the system has to allocate and recycle resources for it, the system overhead is significantly greater than that when creating or undoing a thread.
-
What is the relationship between Java threads and operating system threads?
reference resources: https://www.cnblogs.com/cswiki/p/14676264.html 1.Operating system thread //Implementing threads in user space: a.In the early operating system, all threads were implemented in user space. The operating system can only see the process to which the thread belongs, but not the thread b.In this model, we need to define the data structure, creation, destruction, scheduling and maintenance of threads. These threads run in a process of the operating system, and then the operating system schedules the process directly. c.benefit:The first point is that even if the operating system does not support threads, we can support threads through library functions; Second, thread scheduling only occurs in user state, which avoids the conversion overhead of operating system from kernel state to user state. d.shortcoming:Because the operating system can not see the thread, does not know the existence of the thread, and CPU The time slice switching of is based on the process dimension. Therefore, if a thread in the process takes a long time to operate, because there is no clock interrupt mechanism in the user space, other threads in the process will not be interrupted CPU Long time waiting for resources; In addition, if a thread blocks when making a system call, such as page missing interrupt, the operating system will block the whole process, even if other threads in the process are still working. //Implementing threads in kernel space: a.Kernel level thread is the thread running in the kernel space, which is directly responsible by the kernel and can only be scheduled by the kernel. b.We can directly use the built-in threads in the operating system. The creation, destruction, scheduling and maintenance of threads are directly implemented by the kernel of the operating system. We only need to use system calls instead of designing thread scheduling like user level threads. c.Category: many to one threading model, one to one threading model, many to many threading model 2.Java thread -stay JDK 1.2 Before, Java Threads are based on "Green thread"(Green Threads)It is implemented by user level threads, that is, programmers are responsible for JVM Developed its own thread library or thread management mechanism. -stay JDK 1.2 And later, JVM A more stable and convenient operating system native kernel level thread is selected, and the thread scheduling is handed over to the operating system kernel through system call -That is, in JDK 1.2 And later versions, Java Threads depend largely on the threading model adopted by the operating system, which can not be agreed on different platforms, JVM It is not limited in the specification Java Which thread model does the thread need to use to implement? It may be one-to-one, many to many or many to one. -nowadays Java The essence of thread in is actually the thread in the operating system. Its thread library and thread model largely depend on the specific implementation of the operating system (host system), such as Windows in Java Is based on Wind32 Thread library to manage threads, and Windows The one-to-one threading model is adopted.
-
What is the relationship between the number of core threads, the maximum number of threads, and the queue?
1.As the number of tasks increases, the number of active threads increases. 2.Number of active threads = The number of core threads. At this time, the number of active threads will not be increased, but will be accumulated in the task queue. 3.When the task queue is full, threads will be added based on the number of core threads as the number of tasks increases. 4.Number of active threads = The maximum number of threads cannot be increased. 5.If the task is still increasing, the number of tasks is 11 > Maximum number of threads 8 + Queue length 2, exception thrown RejectedExecutionException,Reject the task. a.The number of active threads initialized by thread pool is 0 b.Number of active threads<If the number of core threads and active threads are executing tasks, the thread pool will generate new threads to execute the submitted tasks c.Number of active threads=Number of core threads,If the active thread is executing a task, the new task will be placed in the blocking queue first d.Number of active threads=Number of core threads,And the active thread is executing tasks, and the blocking queue is full, and there are no active threads<The maximum number of threads, the thread pool will generate a new thread to execute the task e.When a thread is idle, it will be recycled step by step. If no new task is submitted continuously, the number of active threads in the thread pool will be reduced to 0 Priority of new task submission for internal processing in the thread pool: core thread > Blocking queue > Expanded thread
-
Do you understand singleton mode? Come and write it for me! Explain to me the principle of implementing singleton mode with double check lock
public class Singleton { private volatile static Singleton uniqueInstance; // volatile can prohibit instruction rearrangement of the JVM private Singleton() { } public static Singleton getUniqueInstance() { //Judge whether the object has been instantiated before entering the locking code if (uniqueInstance == null) { //Class object locking synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } }
-
continue. . . . . .
4, JAVA Basics
-
Say hashCode()? In what scenario will hashcode () be rewritten?
==And equals?
1.hashCode()Function: obtain hash code, also known as hash code; It actually returns a int Integer. This hash code is used to determine the index position of the object in the hash table. 2.HashCode()Methods and equals()Method is actually used to compare whether two objects are equal a.Rewritten equals()It is generally comprehensive and complex, so the efficiency is relatively low, and the utilization HashCode()For two-way comparison, only one is generated hash Value can be compared, which is more efficient. b.HashCode()Not completely reliable:equals()Equal objects must be equal,HashCode Equal objects are not necessarily equal, and unequal objects must not be equal. 3.Do not rewrite: do not rewrite HashCode Address values are compared, and cannot be compared for reference data types. So it must be rewritten.
4. Rewrite: a.HashTable, HashMap, HashSet b. If equals is rewritten, HashCode must be rewritten
5. If two objects are equal, the hashCode must also be the same; If the two objects are equal, calling the equals method on the two objects returns true; Two objects have the same hashCode value, and they are not necessarily equal; Therefore, if the equals method is overridden, the hashCode method must also be overridden
6. The default behavior of hashCode() is to generate unique values for objects on the heap. If hashCode() is not overridden, the two objects of the class will not be equal in any case (even if they point to the same data)
1.()
-Basic data types: byte,short,char,int,long,float,double,boolean. The comparison between them, using the double equal sign (), compares their values.
-Reference data type: when they compare with (), they compare their storage address in memory
2.equals()
-The equals method cannot act on a variable of a basic data type
-If the equals method is not overridden, the address of the object pointed to by the variable of the reference type is compared (if a class does not override the equals() method, when it compares two objects through equals(), it actually compares whether the two objects are the same object. In this case, it is equivalent to comparing the two objects through ""
-If the equals method is overridden by classes such as String and Date, the content of the object pointed to is compared
2. You're right Java Reflective understanding? stay Java Hump naming is generally adopted in the naming specification. Suppose you want to do something based on reflection. There is a package with many classes in it. How to find out the class name, method name and attribute name that do not meet the specification?
3. Write one Java Class. There may be a class object in the attribute. How to solve the problem of sweeping down layer by layer? (attribute is a class, and there are attributes in the class)
4. When will serialization be used? ```java - The object state in memory is saved to a file or database - A socket transfers objects over a network - adopt RMI Transmission object
-
Polymorphic application scenarios?
-
What are the similarities and differences between interfaces and abstract classes? Must there be abstract methods in the interface? Must there be abstract methods in abstract classes?
1.difference: a.The default method of the interface is public,All methods cannot be implemented in the interface(Java 8 Start interface methods can have default implementations), while abstract classes can have non abstract methods. b.In the interface, except static,final Variable, there can be no other variables, but not necessarily in an abstract class. c.A class can implement multiple interfaces, but can only implement one abstract class. The interface itself can be extends Keyword extends multiple interfaces. d.The default modifier for interface methods is public,Abstract methods can have public,protected and default These modifiers (abstract methods) are meant to be overridden and cannot be used private Keyword modifier!). e.From the design level, abstraction is the abstraction of classes and a template design, while interface is the abstraction of behavior and a specification of behavior. 2.In addition to abstract methods, abstract classes can also have data members and non abstract methods. Abstract classes do not necessarily have abstract methods; But a class that contains an abstract method must be an abstract class 3.All methods in the interface must be abstract( java 8 You can then define default Method, including the method body.), Data members can also be defined in the interface, but they must be constants.
-
What is an immutable class? What are the benefits of String immutability?
-
What are the common data types in Java?
-
What is the difference between JDK dynamic agent and CGLIB dynamic agent?
Part II computer network
-
What is the difference between HTTPS and HTTP? What are the HTTP status codes? Common methods of HTTP? HTTPS is encrypted through SSL. What is the encryption process? How does HTTPS check the public key? What role does CA certificate play and when does it appear?
cost:https The agreement needs to be ca Apply for a certificate. Generally, there are few free certificates and you need to pay a fee. encryption:http It is hypertext transfer protocol, and information is plaintext transmission, https Is safe ssl Encrypted transport protocol. connect:http and https It uses completely different connection methods and different ports,The former is 80,The latter is 443. state:http The connection is simple,Is stateless. Security:HTTPS The agreement is made by SSL+HTTP The network protocol constructed by the protocol can be used for encrypted transmission and identity authentication http Protocol security.
-
What are the reasons for ssl certificate validation failure?
Applied SSL The certificate does not match the site domain name SSL The certificate is invalid and has expired award SSL The digital certification authority for the certificate is not trusted Page contains HTTP Unsafe content
-
The process of domain name resolution into ip when accessing a web address? At what stage does DNS resolution occur? How to solve the DNS hijacking problem?
- Step 1: the client requests domain name resolution,And send the request to the local domain name server. - Step 2: when the local domain name server receives the request,First query the local cache,If there is such record,The local domain name server will directly return the query results. - Step 3: if there is no such record in the local cache,Then the local domain name server sends the request directly to the root domain name server,Then the root domain name server returns a queried domain to the local domain name server(Subdomain of root)The address of the primary domain name server. - Step 4: the local server sends a request to the domain name server returned in the previous step,Then the server that accepts the request queries its own cache,If there is no such record,Returns the address of the related subordinate domain name server - Step 5: repeat step 4,Until the right record is found. - Step 6: the local domain name server saves the returned results to the cache,For next use,The result is also returned to the client. //Enter the url in the browser address bar. What are the protocols? - The browser will be based on your input URL Address to find out whether the domain name is used locally DNS Cache, different browser pairs DNS If the browser caches what you want to access URL Address, then return directly ip. - If you don't cache your URL Address, the browser will initiate a system call to query the local computer hosts Is the file configured ip Address, if found, return directly. - If it cannot be found, initiate a to the network DNS Query. By the root domain name server -> Top level domain name server -> authority DNS After the server, the authoritative server tells the local server the target IP Address, local DNS The server tells the user what to access IP address//Corresponding ip address resolution - The browser needs to be established with the target server TCP connect - Send to server HTTP request - The server processes the request and returns the web page content - The browser parses and renders the page - TCP Four waves and the connection is over DNS Domain name system(DomainNameSystem)The system is used to name computers and network services organized into a domain hierarchy, which can be simply understood as URL Convert to IP Address.
-
How to deal with cross domain issues?
Cross domain means that the browser cannot execute scripts from other websites. It is caused by the browser's homology strategy, which is the browser's right javascript Safety restrictions imposed. 1.JSONP: 2.agent 3.PHP End modification header
-
TCP3 handshakes, 4 waves? Why three handshakes? Not four, five? Why wave four times?
1.3 The reason for the second handshake is to prevent packet loss. If the confirmation of the second server is lost, then c and s Will wait, if the third handshake is used, if it is lost, then s If no confirmation is received, it will be resend. 2.For three times is not necessary, less than three times will have an accident
3.4 reasons for waving: one party cannot disconnect if it wants to
- TCP can only be disconnected when the client and server have no data to send.
- When the client sends FIN message, it can only ensure that the client does not send data.
- After receiving the FIN message from the client, the server can only reply to the client with a confirmation message to tell the client that the server has received your FIN message, but there are still some data on my server. The server can send FIN message to the client only after these data are sent.
6. TCP What are the characteristics? How is flow control implemented? TCP How to ensure security? TCP Tell me again? How to guarantee TCP Reliability of transmission? How is congestion control implemented? 7. token?Why token,no need session?token and session What are the advantages and disadvantages? token and session What's the difference? What is? token? 8. TCP and UDP What's the difference? TCP and UDP What are your usage scenarios? UDP What are the characteristics? 9. What are the network protocols? 10. get and post What's the difference? get and post Which can cache? 11. Do you know about man in the middle attacks? Suppose you attack one HTTPS How to attack your request? 12. HTTP1.1,HTTP2.0,HTTP3.0 What's the difference? 13. TCP/IP Four layer model? and OSI Seven layer model? # Part III operating system 1. In what scenario will deadlock occur? How to avoid deadlock? How do deadlocks occur? Necessary conditions for deadlock? resolvent? 2. Process scheduling algorithm? # Part IV Project 1. Briefly introduce the project 2. What are the challenges in the project? 3. In the project you wrote, how many tables were designed in the database? 4. Is there an index in the table? How is the index designed? 5. Which module in the project is more complex? Technical difficulties? 6. use Redis For caching, how does the data in the cache come from? Redis Have you considered disaster recovery? 7. Before project optimization QPS How much, after optimization QPS How many? 8. With what tools? Under what environment did you deploy and do the pressure test? Jmeter Where was it executed? What is the local configuration for pressure measurement? What points should be considered in environmental deployment for performance pressure testing? 9. When the concurrency is large, check it first redis Cache in, redis If you don't, check it out mysql,Will penetration occur when there is a large amount of concurrency? 10. When the amount of concurrency is large, in the face of the cache penetration problem, for the solution of cache vacancy, when the amount of concurrency is large, requests may directly penetrate to the cache DB Is there a timing problem? 11. Generally speaking, the solution of locking? How to solve the locking problem if it is deployed to multiple machines? Have you learned about distributed locks? 12. MySQL Medium execution SQL Query statement,mysql of server Implementation process of layer? 13. How to update the cache and database when a new record is added? What is the process? 14. use redis Cache login credentials and verification codes? 15. Tell me about the login process? Before logging in, you should first judge whether you have login credentials id Are you? What businesses need to log in after opening the web page? Check your login credentials before logging in redis Are you? Login voucher deposit redis Is the expiration time set in? What does the login certificate contain? Why Redis Store login credentials? use Redis What are the performance improvements in storing login credentials? How to use login credentials? utilize userId,Do you want to query users from the database first? After successful login, you need to log in through the Redis Get login credentials, key What is it and where does it come from? 16. How is the password stored? Why slat Value? 17. In your project redis ,How many masters and followers, how many sentinels? # Part V database ## 1, Redis 1. **redis Basic data types and underlying implementation of**,Reids of String The underlying implementation of the type? ```java //Basic data type 1. String String: can be a string, integer or floating-point number or serialized object (binary security); one key Corresponding to one value 2. List List: linked list. Each node contains a string; Implementation of double ended linked list 3. Set Set: String An unordered collection of types. Set members are unique; Hash table implementation 4. Hash Hash: string Type field(Fields) and value(Value) 5. Zset Ordered set: string Collection of type elements,And duplicate members are not allowed; Each element is associated with a double Score of type. redis It is through scores that the members of the set are sorted from small to large; The members of an ordered set are unique,But score(score)But it can be repeated; Hash table implementation //Underlying implementation
-
What are the application scenarios of Redis? What scenarios do you use Redis? What data structures are used?
-
How to ensure the consistency between cache and database double write? Is there any problem with this method?
1,Cache delay double deletion: delete the cache first, then update the database, sleep for a while (such as 1 second) and delete the cache again.(Delete cache retry mechanism) 3,read biglog Delete cache asynchronously
-
How does Redis implement distributed locks?
-
What are cache penetration, cache breakdown, and cache avalanche? Solution?
-
Redis cluster?
-
Does redis have one master and one slave, three sentinels, or provide a single point of service to the outside world? At this time, three master nodes are introduced. Each master has one slave node and three sentinels, so as to form a redis cluster? A caching service is provided externally as a whole. How to design which primary node the cached key should hit?
-
Explain an IO multiplexing mechanism? Which method is redis implemented in?
-
What are the advantages and disadvantages of Redis persistence RDB and AOF?
-
Redis consistency hash algorithm?
-
Redis expiration deletion policy?
2, MySQL
-
Optimistic lock and pessimistic lock, you know? What are the advantages, disadvantages and application scenarios of optimistic lock and pessimistic lock?
1.Pessimistic lock: each request will first lock the data, then operate the data, and finally unlock it -It can completely ensure the exclusivity and correctness of data -The process of locking and releasing locks will cause consumption, so the performance is not high 2.Optimistic lock: when operating data, the data will not be locked, and the data conflict will not be verified until the data is submitted -Multiple tasks can operate on data in parallel -In the case of very high concurrency, it will lead to a large number of request conflicts and reduce performance
-
How do databases use indexes? Underlying implementation?
-
Innodb's index data structure, back to table mechanism, and differences from mysiam
-
ACID property of transaction, transaction isolation level, and what problems are solved
-
How do you understand database transactions? Isolation level of database transactions? What are the usage scenarios or problems of the isolation levels of these transactions?
-
The difference between dirty reading and fantasy reading? Under what circumstances will unreal reading occur?
-
MySQL isolation level? How is the serialization level achieved?
-
What is the difference between a clustered index and a nonclustered index?
-
Which version of MySQL is used? Which engine do you use? What is the difference between InnoDB and MyISAM?
-
What are the types of multi table connections in a database? What's the difference? What is the difference between the usage of in and exists in the database?
-
How to find pages in MySQL?
-
If there are hundreds of millions of pieces of data in a large amount, can you use limit to find pages?
-
How to design paging in case of large amount of data?
-
Principle of MVCC?
3, Title
- SQL: for table A and table B, if you insert A piece of data at the same time, if you want to ensure the consistency of transactions, you can either succeed or fail at the same time, how should the code be written in JDBC?
- SQL: there is a student curriculum, which records the scores of students in each course. Use an SQL to find all the students with scores greater than 80 points in each course?
- If a MySQL table has five fields a,b,c,d and E, a joint index is established on the four fields a, B, C and D. If where a = 1 and B = 2 and C > 3 and d = 4 during query; Which indexes will go?
Part VI framework
Spring
- How is AOP implemented in Spring?
- The initialization process of Bean in Spring?
- IOC in Spring? Do you have any application scenarios when writing your own code?
- What about the factory mode and usage scenario?
- What design patterns are used in Spring?
- SpringBoot initialization process? Automatic assembly principle?
- How is Spring decoupled? How are dependencies injected?
- Spring MVC?
- What is the difference between SpringBoot and Spring? What is the relationship between Spring, springmvc and SpringBoot?
Part VII design mode
- Design patterns commonly used in Java? What design patterns do you know?
- What is the principle of single responsibility? What is the opening and closing principle? Double inspection single instance mode?
- Say observer mode? And application scenarios?
- Application scenario of singleton mode? How many singleton modes are there?
- What is the difference between static classes and singleton patterns?
- Factory mode usage scenarios? Where did you use it?
- Write a singleton mode? If you write it yourself, which method will you use to create the singleton mode? What are the differences between these singleton patterns?
Part VIII data structure and algorithm
1, Data structure
- What are the benefits of tree structure, what are they useful at ordinary times, and what are the differences between bst and avl trees
- Try to implement the data structure of the next dictionary tree and try to build a dictionary tree.
- What is the difference between arrays and linked lists? Why is the query of array fast? Why is the insertion and deletion of linked list fast? Time complexity of array query, insertion / deletion?
- What is the difference between stack and queue? And application scenarios? How to implement queue with stack? Say ideas
- What are the common data structures?
- How are red and black trees? Other application scenarios of red black tree?
2, Algorithm
- Finding connected components in Undirected Graphs
- Determine whether the binary tree is bst
- Massive data, find duplicate words
- The three threads print 1, 2, and 3 alternately until 100.
- In addition to the B + tree search algorithm, do you know any other search algorithms?
- Code: write a deadlock?
- Code: write a double check singleton mode? Explain the details? Why do you want to perform the second judgment? Is it null? volatile?
- Algorithm: flip every k nodes in the linked list?
- Sorting algorithm? Briefly describe the fast scheduling process?
- What is the difference between fast sorting and bubble sorting?
- Why is the fast scheduling time complexity an O(nlogn)?
- How to look at the time complexity of an algorithm?
- There are 100 million numbers. Given the memory that can only hold 100 numbers, find top5? Say something?
- Suppose there is a 20G file with English words. The words may be repeated. There is only 1 G in the memory. Find out the 10 words with the most English words?
- Algorithm: there is an array of positive integers to find the maximum value of the combination?
Part IX Linux
- Count the number of occurrences of a word in a file with Linux commands?
- Use Linux commands to see which processes are currently active?
- What are the commands for viewing files with Linux?
- less and more know?
- Is Linux used much? What linux commands have you used?
- Signal driven IO and multiplexed IO, you know?