编程知识 cdmana.com

Java common interview questions (interview summary of large enterprises)

1. Say forward (Forward) Redirection (Redirect) The difference between

Forwarding is server behavior , Redirection is client behavior .

forward (Forword)  adopt RequestDispatcher Object's forward(HttpServletRequest request,HttpServletResponse response) Method .RequestDispatcher Can pass HttpServletRequest Of getRequestDispatcher() Methods to get . For example, the following code is to jump to login_success.jsp page .

request.getRequestDispatcher("login_success.jsp").forward(request, response);

Redirect (Redirect)  Is it achieved by using the state returned by the server . When the client browser requests the server , The server will return a status code . Server pass HttpServletRequestResponse Of setStatus(int status) Method setting status code . If the server returns 301 perhaps 302, The browser will request the resource again at the new web address .

  1. From the address bar display : forward Is a server request resource , The server directly accesses the URL, Take that. URL Read the response content of , And then send it back to the browser . The browser has no idea where the content sent by the server comes from , So its address bar is still the original address . redirect It's the server based on the logic , Send a status code , Tell the browser to request that address again . So the address bar is new URL.
  2. In terms of data sharing : forward: Forward page and forward page can be shared request The data in it . redirect: Cannot share data .
  3. From the point of application : forward: It is usually used when users log in , Forward to the corresponding module according to the role . redirect: It is generally used to return to the main page and jump to other websites when users log out and log in
  4. In terms of efficiency : forward: high . redirect: low

2. What is the difference between a process and a thread ? Several ways of communication between processes ? Do you know how to communicate between threads ?

What is the difference between a process and a thread ?

Threads are similar to processes , But a thread is a smaller unit of execution than a process . A process can generate multiple threads during its execution . Unlike processes, multiple threads of the same kind share the same block of memory space and a set of system resources , So the system is generating a thread , Or when switching between threads , The burden is much smaller than the process , That's why , Threads are also known as lightweight processes . in addition , It's also because of sharing resources , Therefore, when executing in a thread, it is generally necessary to synchronize and mutually exclusive . in general , The main difference between processes and threads is that they are different ways of operating system resource management .

Several ways of communication between processes ?

  1. The Conduit (pipe): Pipeline is a half duplex communication mode , Data can only flow in one direction , And it can only be used between related processes . The consanguinity of a process usually refers to the parent-child process relationship . The pipeline is divided into pipe( Nameless pipe ) and fifo( name pipes ) Two kinds of , Famous pipeline is also a half duplex communication mode , But it allows unrelated processes to communicate .
  2. Semaphore (semophore): A semaphore is a counter , It can be used to control the access of multiple processes to shared resources . It's usually used as a locking mechanism , Prevent a process from accessing shared resources , Other processes also access the resource . therefore , Mainly as a means of synchronization between processes and different threads in the same process .
  3. Message queue (message queue): A message queue is a linked list of messages , Stored in the kernel And is identified by the message queue identifier . Message queuing overcomes the lack of signaling information , The pipeline can only support unformatted byte stream and the buffer size is limited . Message queuing is compared to pipeline communication , The advantage is to specify a specific message type for each message , It doesn't need to be in queue order when receiving , Instead, you can receive specific types of messages based on custom conditions .
  4. The signal (signal): Signal is a kind of complex communication mode , Used to inform the receiving process that an event has occurred .
  5. Shared memory (shared memory): Shared memory is mapping a piece of memory that can be accessed by other processes , This shared memory is created by a process , But multiple processes can access , Shared memory is the fastest IPC The way , It is specially designed for the low efficiency of communication between other processes . It often works with other communication mechanisms , If the signal quantity is used together , To achieve synchronization and communication between processes .
  6. Socket (socket): Socket interface is also a communication mechanism between processes , Different from other communication mechanisms, it can be used for different and inter process communication .

Several ways of communication between threads ?

1、 Locking mechanism

  • The mutex : Provides an exclusive way to prevent concurrent modification of data structures .
  • Read-write lock : Allow multiple threads to read shared data at the same time , And write operations are mutually exclusive .
  • Condition variables, : Processes can be blocked atomically , Until a particular condition is true . Conditional testing is done under the protection of mutex . Conditional variables are always used with mutexes .

2、 Semaphore mechanism : Including nameless thread semaphores and named thread semaphores

3、 Signaling mechanism : Similar to signal processing between processes .

The main purpose of inter thread communication is for thread synchronization , So threads have no communication mechanism for data exchange like process communication .

3. Why use singleton mode ? Handwriting several thread safe singleton modes ?

Simply put, using singleton mode can bring the following benefits :

  • For frequently used objects , You can omit the time it takes to create an object , For those heavyweight objects , It's a very significant overhead ;
  • because new Reduce the number of operations , Therefore, the frequency of using system memory will be reduced , This will lessen GC pressure , To shorten the GC Pause time .

Slacker type ( Double check locked version )

public class Singleton {

    //volatile Guarantee , When uniqueInstance Variable is initialized to Singleton When an instance , Multiple threads can handle uniqueInstance Variable 
    private volatile static Singleton uniqueInstance;
    private Singleton() {
    }
    public static Singleton getInstance() {
       // Check instance , If it doesn't exist , Go to sync code block 
        if (uniqueInstance == null) {
            // Only for the first time can the code here be executed completely 
            synchronized(Singleton.class) {
               // After entering the synchronization code block , Check again , If it is still null, To create an instance 
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

Static inner class mode

The singleton of static internal implementation is lazy and thread safe .

Only by explicitly calling getInstance When the method is used , To explicitly load SingletonHolder class , To instantiate instance( Only when the instance of this singleton is used for the first time can it be loaded , There will be no thread safety issues ).

public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
}

4. A brief introduction bean. know Spring Of bean The scope and life cycle of ?

stay Spring in , The subjects that make up the application and the Spring IOC Objects managed by containers , It's called bean. Simply speak ,bean Is the IOC Container initialization 、 Objects of assembly and management , besides ,bean It's no different from other objects in the application . and bean And bean The interdependencies between them will be described by configuration metadata .

Spring Medium bean By default, it's single , These single examples Bean How to ensure thread safety in multithreaded programs ? For example, for Web applications ,Web The container creates a separate... For each user request Sevlet Thread to process the request , introduce Spring After the framework , Every Action It's all singletons , So for Spring A single example of hosting Service Bean, How to ensure its safety ? Spring Our single example is based on BeanFactory That is to say Spring Container of , Single case Bean There is only one... In this container ,Java Our single example is based on JVM, Every JVM There is only one example .

5.Spring Do you understand the transaction communication behavior in ?TransactionDefinition Which five constants in the interface represent the isolation level ?

Transaction propagation behavior

Transaction propagation behavior ( In order to solve the transaction problem that business layer methods call each other ): When a transaction method is called by another transaction method , You must specify how transactions should propagate . for example : Method may continue to run in an existing transaction , It's also possible to start a new business , And run... In your own transaction . stay TransactionDefinition Several constants representing propagation behavior are included in the definition :

Support for current transactions :

  • TransactionDefinition.PROPAGATION_REQUIRED: If there are currently transactions , Then join the transaction ; If there is no current transaction , Create a new transaction .
  • TransactionDefinition.PROPAGATION_SUPPORTS: If there are currently transactions , Then join the transaction ; If there is no current transaction , Continue to run in a non transactional manner .
  • TransactionDefinition.PROPAGATION_MANDATORY: If there are currently transactions , Then join the transaction ; If there is no current transaction , Throw an exception .(mandatory: mandatory )

The current transaction is not supported :

  • TransactionDefinition.PROPAGATION_REQUIRES_NEW: Create a new transaction , If there are currently transactions , Suspend the current transaction .
  • TransactionDefinition.PROPAGATION_NOT_SUPPORTED: Run in a non transactional manner , If there are currently transactions , Suspend the current transaction .
  • TransactionDefinition.PROPAGATION_NEVER: Run in a non transactional manner , If there are currently transactions , Throw an exception .

Other situations :

  • TransactionDefinition.PROPAGATION_NESTED: If there are currently transactions , Create a transaction to run as a nested transaction of the current transaction ; If there is no current transaction , Then the value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED.

Isolation level

TransactionDefinition Five constants representing the isolation level are defined in the interface :

  • TransactionDefinition.ISOLATION_DEFAULT:  Use the default isolation level of the back-end database ,Mysql Default adopted REPEATABLE_READ Isolation level Oracle Default adopted READ_COMMITTED Isolation level .
  • TransactionDefinition.ISOLATION_READ_UNCOMMITTED:  Lowest isolation level , Allow read of uncommitted data changes , Can cause dirty reading 、 Phantom or unrepeatable reading
  • TransactionDefinition.ISOLATION_READ_COMMITTED:  Allow to read data submitted by concurrent transactions , Can prevent dirty reading , But phantom or unrepeatable reads can still occur
  • TransactionDefinition.ISOLATION_REPEATABLE_READ:  Multiple reads of the same field are consistent , Unless the data is modified by the transaction itself , Can prevent dirty and unrepeatable read , But phantom reading can still happen .
  • TransactionDefinition.ISOLATION_SERIALIZABLE:  Highest isolation level , Completely obey ACID Isolation level . All transactions are executed one by one , In this way, there is no interference between transactions , in other words , This level prevents dirty reads 、 Unrepeatable reading and phantom reading . But this will seriously affect the performance of the program . This level is not usually used .

6.SpringMvC Operation principle

The client sends the request -> Front controller DispatcherServlet Accept client requests -> Find the processor map HandlerMapping Parse the request corresponding to Handler-> HandlerAdapter Will be based on Handler To call the real processor to open the request , And deal with the corresponding business logic -> The processor returns a model view ModelAndView -> View parser for parsing -> Returns a view object -> Front controller DispatcherServlet Render data (Moder)-> Return the resulting view object to the user


Based on my many years of working experience and learning experience , Recorded a new set of Java Focus on video tutorials , If you are learning now Java, At the beginning of learning Java There is no systematic learning course in the process , You can add groups 654631948 Collect the learning materials , Interview questions , Development tools, etc , There are senior people in the group java The teacher answers questions , Every day, there will also be live lectures on the basic part and architecture , You can also add my wechat renlliang2013 In depth communication .

 

java Basic course :https://ke.qq.com/course/149432?tuin=57912c43


Java Distributed Internet Architecture / Microservices / High performance /springboot/springcloud:

https://ke.qq.com/course/179440?tuin=57912c43

 

 

版权声明
本文为[renlianggee]所创,转载请带上原文链接,感谢

Scroll to Top