Java interview questions

1. Talk about your understanding of MVC in combination with the project.
MVC is the abbreviation of model-view-control. That is, model-view-controller. MVC is a design pattern, which is mandatory for the input, processing, and output of the application. Separate. Model, view and controller in MVC undertake different tasks.
View: View is the interface that the user sees and interacts with. The view displays relevant data to the user and accepts the user's output. The view does not perform any business Logical processing
Model : represents business data and business processing, equivalent to JavaBean. A model can provide data for multiple views, which provides reusability of the application.
Controller: When the user submits the button in the single-machine web page, the controller receives Request and call the corresponding model to process the request. Then call the corresponding view according to the processing structure to display the structure
of the processing process MVC processing process: First, the controller receives the user's request, calls the corresponding model for business processing, and returns data Call the corresponding view to the controller. The controller calls the corresponding view to display the processing structure. And presents it to the user through the view. If the project corresponds to the haul of MVC; the View pair uses the JSP.controler in the project corresponding to the action.model corresponding to the service+dao layer The business logic and operations of the persistence layer

2. Why use ssh in the project (the advantages of the three major frameworks)
- springmvc is because struts is based on the mvc mode, which layers the application well, making developers pay more attention to the implementation of business logic
- Hibernate: because of Hibernate Provides an easy-to-use and efficient object-relational mapping framework for java applications. hibernate is a lightweight persistence layer framework with rich functions
- Spring's framework based on IOC (inversion of control) and AOP framework multi-layer J2ee system

3. Why use spring
spring is a lightweight inversion of control (IOC), aspect-oriented (AOP), interface-oriented, transaction management, and inclusive to promote other frameworks; the degree of coupling of other frameworks used in the system is greatly reduced Easy to use, easy to use and easy to manage..

4. How does Spring act as a glue
in the project? Using spring's ioc (inversion of control or dependency injection) in the project, clearly defining the component interface (UserDao), developers can develop each component independently, and then according to the dependencies between components Relational assembly (UserControl depends on UserService, UserService depends on UserDao) runs, it is very good to combine SpringMVC and hibernate;
spring's transaction management, hibernate configures things for database operations

5. Describe how spring things are used to control
spring things in the system, including programming and declarative transactions. The declarative transaction management used in the system is implemented with spring's AOP; read-only things and rollback things are configured , When an error occurs, the transaction is rolled back. In the project, the transaction daoservice layer is cut through aop, so that business logic operations, including several data operations, can be controlled in one transaction.

6.Hibernate working principle and what to use?
Principle:

  • Read and parse configuration files
  • Read and parse the mapping information, create a SessionFactory
  • Open Session
  • Create a transaction Transaction
  • Endurance operation
  • Submit things
  • close session

  • Why use SessionFactory to close
    1. Encapsulate the JDBC access database code, which greatly simplifies the tedious and repetitive code of the data access layer.
    2. Hibernate is a mainstream persistence framework based on JDBC and an excellent ORM implementation. Simplify the coding work of the DAO layer to a large extent.
    3.Hibernate uses Java reflection mechanism instead of bytecode enhancement program to achieve transparency
    4.Hibernate's performance is very good, because he is a lightweight framework. The flexibility of mapping Excellent. He supports all kinds of relational databases, from one to many to many complex relationships

Hibernate's optimization strategy used in the system
Hibernate's data cache includes two levels: the first level cache, which is performed at the session level, mainly for object caching, and the id is the key to save the object, which exists during the life of the session; two Level 1 cache, which is performed at the level of SessionFactory, has object cache and query cache. Query cache - query condition is the key to save query results. It exists during the life of SessionFactory. By default, Hibernate only enables level 1 cache.

Comparison of
Hibernate and mybatis Compared with Hibernate and mybatis, mybatis is more lightweight, flexible and easy to master. Mybatis can separate sql statements from java code and write them in configuration files, which greatly reduces the coupling between java code and SQL statements, making it easier to operate sql statements. The important thing is that mybatis can also write dynamic sql statement, but mybatis also has some defects. For example, the caching mechanism of mybatis itself is not as perfect as that of hibernate. In addition to its own good caching mechanism, hibernate can also use third-party caching. Hibernate encapsulates JDBC more completely, but it is more difficult to learn than mybatis. Hibernate's DAO layer development is simpler than MyBatis, and the maintenance and caching of objects is better than MyBatis.

Talk about the difference between interceptors and filters
- interceptors are based on the JAVA reflection mechanism, while filters are based on function callbacks
- filters can only work on Action requests (methods in action), while filters can All requests work (css JSP JS)
- the filter depends on the servlet container, the second interceptor does not depend on the servlet container

Is SessionFactory thread-safe? Is Session thread-safe? Can two threads share a Session?
SessionFactory corresponds to the concept of a data storage in Hibernate. Its threads are safe and can be accessed concurrently by multiple threads. SessionFactory generally only It will be created at startup. For the corresponding program, it is best to encapsulate the SessionFactory through a singleton mode for access

Session is a lightweight non-thread-safe object (session cannot be shared between threads), which represents a unit of work that interacts with the database. Session is created by SessionFactory and is closed after the task is completed. Session is a persistence layer service The main interface provided externally. Sessions acquire database connections lazily (that is, they are acquired only when needed). In order to avoid creating too many sessions, you can use TreadLocal to get the current session, no matter how many times you call the getCurrentSession() method, the same session is returned.

The difference between Session's load and get methods
If no eligible records are found, the get method returns a null value, while the load method throws an exception. The
get method directly returns the entity class object, and the load method returns the proxy of the entity class object.
For the load() method , Hibernate thinks that the data must exist in the database, you can safely use the proxy to implement lazy loading, if there is no data, an exception will be thrown, and the get() method to fetch data may not exist.

The process of loading entity objects in the
session Before calling the data query tool, the session will first query in the buffer, and in the first-level cache, query through the entity type and primary key. If the first-level cache query is in progress and the data status is legal, then Return
If the first-level cache is not hit, then the session will query in the current NonExists record (equivalent to a query blacklist, if there are repeated invalid queries, it can be quickly judged to improve performance), if the same query conditions exist in NonExists , then returns null;
for the load method, if the first-level cache query fails, the second-level cache is queried, and if the second-level cache hits, it returns directly.
If the previous query is not hit, the sql statement is issued, if the query does not find the corresponding record , the query is added to the NonExists of the Session to record, and returns null;
according to the mapping configuration and SQL statement, the ResultSet is created, and the corresponding entity object is created
Put the object into the Session (first-level cache) management
Execute the onload of the interceptor method (if there is a corresponding interceptor);
put the data object into the second level cache;
return the data object.

What is the difference between the list method and the iterate method of the Query interface?
①Each object returned by the list() method is complete (every attribute in the object is filled with fields in the table), the list method cannot use the cache, it only writes to the first-level cache but does not read it;

②The iterate method can make full use of the first-level cache. The object it returns only contains the primary key value (identifier). Only when you operate on the object in the iterator, Hibernate will send the SQL statement to the database again to obtain the the property value of the object;

②The list method will not cause the N+1 query problem, while the iterate method will cause the N+1 query problem.

How Hibernate implements paging query
Through Hibernate to implement paging query, the developer only needs to provide the HOL statement, the number of query starting rows (setFirstResult() method) and the maximum number of query rows (setMaxResult()), and call the list() of the Query interface method, Hibernate will automatically generate SQL statements for paging queries

The execution process of servlet The
client sends an http request, the web server request is forwarded to the servlet container, the servlet container parses the url and finds the corresponding servlet according to werb.xml, and passes the request and response objects to the found servlet, and the servlet can know according to the request. Who sent the request, request information and other information, when the servlet processes the business logic, it will put the information into the response and respond to the client.

The springMVC execution process
The springMVC process is a layered control framework with dispatchservlet as the core. First, the client sends a request to the web server to parse the request url and match the mapped url of the dispatchservlet. If it matches, put the request into the dispatchservlet. Mapping mapping configuration to find the corresponding handel, and then hand over the processing right to the found handel. The handel encapsulates the code for processing business logic. When the handel is processed, it will return a logical view modelandview to the dispatchservlet. At this time, modelandview is a logic The view is not a formal view, so the dispatchservlet will parse the modelandview through the viewresource view resource, and then put the parsed parameters into the view and return it to the client for display.

Multi-threading
a) A process is an independent operating environment, which can be regarded as a program, and a thread can be regarded as a task of the process. For example, QQ is a process, and a QQ window is a thread.

b) In a multi-threaded program, multi-threaded concurrency can improve the efficiency of the program. The cpu will not enter an idle state because a thread is waiting for resources, it will give the resources to other threads.

c) The user thread is the thread created by our development program, and the daemon thread is the system thread, such as the GC in the JVM virtual

d) The priority level of the thread: each thread has a priority level, and the one with a higher limited level can obtain CPU resources first to make the thread transition from the ready state to the running state. It is also possible to customize the limited level of threads

e) Deadlock: At least two or more threads strive for more than two cpu resources, to avoid deadlock, avoid using nested locks, only need to lock where they need to be synchronized and avoid infinite waiting

Spring's IOC and AOP
a) IOC: Spring is an open source framework. Using a framework can reduce workload and improve work efficiency. It is a layered structure, that is, the corresponding layer handles the corresponding business logic and reduces the coupling of the code. The core of spring is IOC inversion of control and AOP aspect-oriented programming. IOC control inversion mainly emphasizes that the relationship between programs is controlled by the container, the container controls the object, and controls the acquisition of external resources. The reverse is that in traditional programming, we create objects to obtain dependent objects, while in IOC, the container helps us create objects and inject dependent objects. It is the container that helps us find and inject objects, and objects are acquired. , so it is called inversion.

b) AOP: Aspect-oriented programming, mainly to manage the business of the system layer, such as logs, permissions, things, etc. AOP is to split the encapsulated object, find out the common behavior that affects multiple objects, and encapsulate it into a reusable module, this module is named aspect (aspect), the aspect connects those with business logic Unrelated, but is extracted and encapsulated by the logic commonly called by the business modules, which reduces the repetitive code in the system, reduces the coupling between modules, and improves the maintainability of the system.

Hibernate's core idea
Hibernate's core idea is the ROM object-relational mapping mechanism. It maps operations between tables to operations between objects and objects. That is, the information extracted from the database will be automatically encapsulated into specific objects according to the mapping requirements you set. Therefore, hibernate makes the modification of the object correspond to the modification of the data row by mapping the entity class of the data table.

Mybatis
database optimization
a) Select the appropriate field, for example, the mailbox field can be set to char (6), try to set the field to notnull, so that the database does not need to compare the null value when
querying b) Use the associated query (left join on) query instead of subquery

c) Manually create temporary table using union union query

d) Open the transaction, when the database executes multiple statements and there is an error, the transaction will be rolled back, which can maintain the integrity of the database

e) Using foreign keys, things can maintain the integrity of data but it cannot guarantee the relevance of data, using foreign keys can ensure the relevance of data

f) Using an index, an index is a common method to improve database performance, it can make the database server retrieve specific rows much faster than no index, especially for max, min, order by queries, the effect is more obvious

g) Optimized query statements. In most cases, the use of indexes can improve the speed of the query, but if the SQL statements are not used properly, the indexes cannot exert their characteristics.

Tomcat server optimization (memory, concurrent connections, cache)
a) Memory optimization: mainly to optimize the Tomcat startup parameters, we can modify its maximum memory number in the Tomcat startup script and so on.

b) Optimization of the number of threads: Tomcat's concurrent connection parameters are mainly configured in server.xml in the Tomcat configuration file, such as modifying the minimum number of idle connection threads to improve system processing performance and so on.

c) Optimize the cache: Turn on the compression function and modify the parameters. For example, the default size of the compressed output content is 2KB, which can be modified appropriately.

When the class loading process
encounters a new class, it will first go to the method area to find the class file. If it is not found, it will go to the hard disk to find the class file. After it is found, it will return and load the class file into the method area. When the static member variable is allocated to the static area of ​​the method area, the non-static member variable is allocated to the non-static area, and then starts to initialize the static member variable and assigns the default value. After the default value is assigned, it will be written according to the static member variable. The position of the display value is assigned, and then the static code is executed. Class loading is complete when all static code has been executed

Object creation
a) When a new class is encountered, the class will be loaded and the class file will be located

b) All static member variables are initialized, the static code block will also be executed, and only executed once when the class is loaded

c) When a New object is created, the jvm will allocate a large enough storage space in the heap

d) The storage space is cleared, default values ​​are assigned to all variables, and all object references are assigned null

e) Give the field some initialization operations according to the writing position

f) call the constructor method (no inheritance)

MyBatis programming steps
1. Create SqlSessionFactory
2. Create SqlSession through SqlSessionFactory
3. Perform database operations through sqlsession
4. Call session.commit() to submit things
5. Call session.close() to close the session

How to communicate between processes?
(1) Pipes and named pipes: Pipes can be used for communication between parent and child processes with affinity. In addition to the functions of pipes, named pipes also allow communication between unrelated processes.

(2) Signal: Signal is a simulation of the interrupt mechanism at the software level. It is a relatively complex communication method used to notify the process that an event has occurred. A process receives a signal and the processor receives it. An interrupt request can be said to be consistent in effect.

(3) Message queue (message queue): The message queue is a linked list of messages. It overcomes the shortcomings of the limited semaphore in the above two communication methods. Processes with write permissions can add new information to the message queue according to certain rules. ; Processes that have read permission on the message queue can read information from the message queue.

(4) Shared memory: It can be said that this is the most useful way of inter-process communication. It enables multiple processes to access the same memory space, and different processes can see the update of the data in the shared memory in the other process in time. This method requires some kind of synchronization operation, such as mutex and semaphore.

(5) Semaphore (semaphore): It is mainly used as a means of synchronization and mutual exclusion between processes and between different threads of the same process.

(6) Socket (socket): This is a more general inter-process communication mechanism, which can be used for inter-process communication between different machines in the network, and is widely used.

The basic concept of thread, the basic state of thread and the relationship between states?
A thread is the smallest unit that performs operations in a process, an entity in the process, and a basic unit that is independently scheduled and dispatched by the system. All resources owned by the process are shared with other threads belonging to the same process. A thread can create and cancel another thread, and multiple threads in the same process can execute concurrently.

produce ready run demise blocking

Daemon thread: As long as any non-daemon thread in the current JVM has not ended, the daemon thread will all work thread.setDaemon(true)

The priority of the thread (1–>10 (most important))

It is recommended to use implemenets Runnable
to retain the right of inheritance. It is
suitable for multiple identical program codes to go to the same resource
. It increases the robustness of the program, and the code can be shared by multiple threads. The code and data are independent

Difference between thread and process?
(1) A thread can only belong to one process, and a process can have multiple threads, but at least one thread.
(2) Resources are allocated to a process, and all threads of the same process share all the resources of the process.
(3) The processor is assigned to the thread, that is, the thread is really running on the processor.
(4) During the execution process of threads, cooperative synchronization is required. Threads of different processes should be synchronized by means of message communication. A thread is an execution unit within a process and a schedulable entity within a process.

The synchronization methods between threads can be roughly divided into two categories: user mode and kernel mode. As the name implies, the kernel mode refers to the use of the singleness of the system kernel object for synchronization. When using it, it is necessary to switch between the kernel mode and the user mode, and the user mode does not need to switch to the kernel mode, and only completes the operation in the user mode.
User-mode methods are: atomic operations (eg a single global variable), critical sections. The methods in kernel mode are: event, semaphore, mutex

What are the similarities and differences between multi-threaded synchronization and mutual exclusion, and under what circumstances are they used?
The so-called synchronization refers to a number of program fragments scattered among different processes, and their operation must be executed in strict accordance with a prescribed sequence, which depends on the specific tasks to be completed. If defined in terms of access to resources, synchronization refers to the orderly access of visitors to resources through other mechanisms on the basis of mutual exclusion (in most cases). In most cases synchronization already implements mutual exclusion, in particular all writes to resources must be mutually exclusive. In a few cases, it is possible to allow multiple visitors to access the resource at the same time.

The so-called mutual exclusion refers to several program fragments scattered among different processes. When a process runs one of the program fragments, other processes cannot run any of them, and can only wait until the process finishes running the program. After the program fragment can be run. If defined by access to resources, mutual exclusion of a resource allows only one visitor to access it, which is unique and exclusive. But mutual exclusion cannot limit the order in which visitors access resources, that is, the access is unordered.

What is the difference between calling wait() and sleep() methods in Java multithreading?
Both wait and sleep in Java programs cause some form of pause, and they can meet different needs. The wait() method is used for inter-thread communication. If the wait condition is true and other threads are woken up, it will release the lock, while the sleep() method only releases CPU resources or stops the current thread from executing for a period of time, but does not release the lock.

What is the difference between "==" and equals method?
The == operator is specially used to compare whether the values ​​of two variables are equal, that is, to compare whether the values ​​stored in the memory corresponding to the variables are the same, to compare whether two basic types of data or two reference variables are equal, Only use the == operator.

The quals method is used to compare whether the contents of two independent objects are the same, just like comparing whether two people look the same, the two objects it compares are independent

. The difference between an abstract class and an interface?
 Abstract methods must be modified with the abstract keyword. If a class contains abstract methods, the class is called abstract class, and the abstract class must be modified with the abstract keyword before the class.
 1) The abstract method must be public or protected (because if it is private, it cannot be inherited by subclasses, and subclasses cannot implement the method), and the default is public by default.

  2) Abstract classes cannot be used to create objects;

  3) If a class inherits from an abstract class, the subclass must implement the abstract method of the superclass. If the subclass does not implement the abstract method of the superclass, the subclass must also be defined as an abstract class.

Differences?
1. Differences at the grammatical level

  1) Abstract classes can provide implementation details of member methods, while only public abstract methods exist in interfaces;

  2) Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type;

  3) An interface cannot contain static code blocks and static methods, while abstract classes can have static code blocks and static methods;

  4) A class can only inherit one abstract class, but a class can implement multiple interfaces.

Explain how Nginx handles HTTP requests
Nginx uses the reactor pattern. The main event loop waits for the operating system to signal a ready event so data can be read from the socket, in that instance the buffer is read and processed. A single thread can provide tens of thousands of concurrent connections.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325759896&siteId=291194637