Summary of java interview questions (below)

foreword

  From the last article , we will gradually introduce you to the summary of answers to some of the most common questions in the java interview summary. It's still the same sentence to give everyone the answer I think is more correct for each interview question. Some of them are what I think, and some are excerpted from the answers of others on the Internet. There may be mistakes, so before everyone adopts it, you must think about whether it is correct, but it should be correct. If you find an error, I also hope that you will give the correct answer in the message area for your reference.
  The last article introduced to you the most basic common interview questions in java in java and a summary of common interview questions in java containers.

1. Multithreading

1. What is the difference between parallelism and concurrency?

  • Parallel : Multiple processors or multi-core processors process multiple tasks simultaneously.
  • Concurrency : Multiple tasks on the same CPU core are executed in turn (alternately) according to subdivided time slices. Logically, those tasks are executed at the same time.

2. What is the difference between a thread and a process?

  A program has at least one process, a process has at least one thread, and a process can have multiple threads to increase the execution speed of the program.

3. What is the daemon thread?

  A daemon thread is a special kind of process that runs in the background. It is independent of the controlling terminal and periodically performs some kind of task or waits for some event to occur. In Java, garbage collection threads are special daemon threads.

4. What are the ways to create a thread?

   There are three ways to create a thread:
  • Inherit Thread and override the run method;
  • Inherit Thread and override the run method;
  • Implement the Callable interface.

5. What is the difference between runnable and callable?

  Runnable has no return value, callable can get return value, callable can be regarded as a supplement to runnable.

6. What is the status of the thread?

  The state of the thread:
   • NEW has not been started
   • RUNNABLE is being executed
   • BLOCKED blocked (blocked by synchronization lock or IO lock)
   • WAITING permanent waiting state
   • TIMED_WAITING waiting for the specified time to be reawakened
   • TERMINATED execution completed

7. What is the difference between sleep() and wait()?

   • Different classes : sleep() comes from Thread and wait() comes from Object.
   • Release the lock : sleep() does not release the lock; wait() releases the lock.
  • Different usage : sleep() will automatically resume when time is up; wait() can be woken up directly using notify()/notifyAll().

8. What is the difference between notify() and notifyAll()?

   notifyAll() wakes up all threads, and wakes up a thread after notify(). After notifyAll() is called, all threads will be moved from the waiting pool to the lock pool, and then participate in the competition of the lock. If the competition is successful, the execution will continue. If it is unsuccessful, it will stay in the lock pool and wait for the lock to be released and participate in the competition again. The notify() will only wake up one thread, and which thread to wake up is controlled by the virtual machine.

9. What is the difference between run() and start() of a thread?

  The start() method is used to start the thread and the run() method is used to execute the thread's runtime code. run() can be called repeatedly, while start() can only be called once.

10. What are the ways to create a thread pool?

  There are seven ways to create a thread pool, and the core is the last one:
   • newSingleThreadExecutor(): Its characteristic is that the number of worker threads is limited to 1, and it operates an unbounded work queue, so it ensures that all tasks are executed by Sequential execution, at most one task will be active, and users are not allowed to change the thread pool instance, so it can avoid changing the number of threads;
  • newCachedThreadPool(): It is a thread pool used to process a large number of short-term work tasks , has several distinctive features: it tries to cache threads and reuse them, and when no cached threads are available, new worker threads are created; if a thread is idle for more than 60 seconds, it is terminated and moved out of the cache; when idle for a long time , this thread pool will not consume any resources. It uses SynchronousQueue internally as a work queue;
   • newFixedThreadPool(int nThreads): reuses a specified number (nThreads) of threads, behind which an unbounded work queue is used, and at most nThreads worker threads are active at any time. This means that if the number of tasks exceeds the number of active queues, it will wait for an idle thread to appear in the work queue; if a worker thread exits, a new worker thread will be created to make up the specified number of nThreads;
   • newSingleThreadScheduledExecutor() : Create a single-threaded pool and return ScheduledExecutorService, which can schedule or periodic work;
   • newScheduledThreadPool(int corePoolSize):Similar to newSingleThreadScheduledExecutor(), it creates a ScheduledExecutorService that can perform scheduled or periodic work scheduling, the difference is a single worker thread or multiple worker threads;
   • newWorkStealingPool(int parallelism): This is a thread pool that is often overlooked. This creation method was added in Java 8. ForkJoinPool is built internally, and the Work-Stealing algorithm is used to process tasks in parallel, and the processing order is not guaranteed;
   • ThreadPoolExecutor(): It is the most primitive thread pool creation. The above 1-3 creation methods are all It is the encapsulation of ThreadPoolExecutor.

11. What are the states of the thread pool?

  • RUNNING : This is the most normal state, accepting new tasks and processing tasks in the waiting queue.
  • SHUTDOWN : Does not accept new task submissions, but will continue to process tasks in the waiting queue.
  • STOP : Do not accept new task submissions, no longer process tasks in the waiting queue, and interrupt the thread that is executing the task.
  • TIDYING : All tasks are destroyed, workCount is 0, and the hook method terminated() will be executed when the state of the thread pool is converted to TIDYING state.
  • TERMINATED : After the terminated() method ends, the state of the thread pool will become this.

12. What is the difference between the submit() and execute() methods in the thread pool?

   • execute() : Only tasks of type Runnable can be executed.
  • submit() : Can perform tasks of type Runnable and Callable.
  Callable type tasks can get the return value of execution, while Runnable execution has no return value.

13. How to ensure the safety of multi-threading in Java programs?

   • Method 1 : Use safe classes, such as classes under Java.util.concurrent.
   • Method 2 : Use automatic lock synchronized.
   • Method 3 : Use manual lock Lock.

   The manual lock Java code is implemented as follows:

package com.ph.Interview;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
    
    
	public static void main(String[] args) {
    
    
		Lock lock = new ReentrantLock();
		lock. lock();
		try {
    
    
		    System. out. println("获得锁");
		} catch (Exception e) {
    
    
		    // TODO: handle exception
		} finally {
    
    
		    System. out. println("释放锁");
		    lock. unlock();
		}

	}
}

   The specific execution results are as follows:

14. What is the principle of synchronized lock escalation in multithreading?

   Synchronized lock upgrade principle : There is a threadid field in the object header of the lock object. When accessing for the first time, the threadid is empty. The jvm allows it to hold a biased lock, and sets the threadid to its thread id. When it enters again, it will be First judge whether the threadid is consistent with its thread id. If it is consistent, you can use this object directly. If it is inconsistent, upgrade the biased lock to a lightweight lock, and obtain the lock by spinning a certain number of times. After executing a certain number of times, if it is not normal Once the object to be used is obtained, the lock will be upgraded from a lightweight to a heavy-weight lock. This process constitutes the upgrade of the synchronized lock.
   The purpose of lock escalation: Lock escalation is to reduce the performance consumption caused by locks. After Java 6, the implementation of synchronized is optimized, and the biased lock is upgraded to a lightweight lock and then upgraded to a heavyweight lock, thereby reducing the performance consumption caused by the lock.

15. What is deadlock?

   When thread A holds exclusive lock a and tries to acquire exclusive lock b, while thread B holds exclusive lock b and tries to acquire exclusive lock a, it will happen that two threads AB hold each other's needs due to The blocking phenomenon that occurs is called deadlock.

16. How to prevent deadlock?

   • Try to use the tryLock(long timeout, TimeUnit unit) method (ReentrantLock, ReentrantReadWriteLock), set the timeout time, and the timeout can exit to prevent deadlock.
   • Try to use Java.util.concurrent concurrent classes instead of hand-written locks.
  • Try to reduce the granularity of the use of locks, and try not to use the same lock for several functions.
  • Minimize synchronized code blocks.

17. What is ThreadLocal? What are the usage scenarios?

   ThreadLocal provides an independent copy of the variable for each thread that uses the variable, so each thread can change its own copy independently without affecting the copies of other threads.
  The classic usage scenarios of ThreadLocal are database connection and session management.

18. Tell me about the underlying implementation principle of synchronized?

   Synchronized is implemented by a pair of monitorenter/monitorexit instructions, and the monitor object is the basic implementation unit of synchronization. Before Java 6, the implementation of monitor completely relied on the mutual exclusion lock inside the operating system. Because it needs to switch from user mode to kernel mode, the synchronization operation is an indiscriminate heavyweight operation, and the performance is also very low. But in Java 6, the Java virtual machine has made a drastic improvement on this, providing three different monitor implementations, which are often referred to as three different locks: Biased Locking, Lightweight Locking and Heavyweight lock with greatly improved performance.

19. What is the difference between synchronized and volatile?

   • volatile is a variable modifier; synchronized is a modifier class, method, and code segment.
  • volatile can only achieve the modification visibility of variables and cannot guarantee atomicity; while synchronized can guarantee the modification visibility and atomicity of variables.
  • volatile will not cause thread blocking; synchronized may cause thread blocking.

20. What is the difference between synchronized and Lock?

   • synchronized can lock classes, methods, and code blocks; while lock can only lock code blocks.
  • Synchronized does not require manual acquisition and release of locks. It is simple to use. An exception will automatically release the lock without causing a deadlock; while lock needs to lock and release the lock by itself. deadlock.
  • Through Lock , you can know whether the lock has been successfully acquired, but synchronized cannot.

21. What is the difference between synchronized and ReentrantLock?

   The early implementation of synchronized is relatively inefficient. Compared with ReentrantLock, the performance of most scenarios is quite different, but a lot of improvements have been made to synchronized in Java 6.
  The main differences are as follows:
  • ReentrantLock is more flexible to use, but there must be a cooperative action to release the lock;
  • ReentrantLock must acquire and release the lock manually, while synchronized does not need to manually release and open the lock;
  • ReentrantLock is only applicable to code block locks, while synchronized Can be used to decorate methods, code blocks, etc.
  • Variables marked volatile are not optimized by the compiler; variables marked synchronized can be optimized by the compiler.

22. Tell me about the principle of atomic?

   atomic mainly uses CAS (Compare And Wwap) and volatile and native methods to ensure atomic operations, thereby avoiding the high overhead of synchronized and greatly improving the execution efficiency.

2. Reflection

1. What is reflection?

   Reflection is that in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this kind of dynamically obtained information and dynamic invocation of objects The functionality of a method is called the reflection mechanism of the Java language.

2. What is Java serialization? When is serialization required?

  Java serialization is to save the state of various objects in memory, and the saved object state can be read out.
  Java serialization is required in the following situations:
  • When you want to save the state of an object in memory to a file or database;
  • When you want to use sockets to transfer objects over the network;
  • When you want to use RMI (remote method invocation) when transferring objects.

3. What is dynamic proxy? What applications are there?

  Dynamic proxies are dynamically generated proxy classes at runtime.
  The application of dynamic proxy includes spring aop, hibernate data query, back-end mock, rpc of test framework, Java annotation object acquisition, etc.

4. How to implement dynamic proxy?

  JDK native dynamic proxy and cglib dynamic proxy. JDK native dynamic proxy is implemented based on interfaces, while cglib is implemented based on subclasses that inherit the current class.

3. Object copy

1. Why use clone?

   The cloned object may contain some properties that have been modified, and the properties of the new object are still the values ​​at the time of initialization, so when a new object is needed to save the "state" of the current object, the clone method is used.

2. How to implement object cloning?

   • Implement the Cloneable interface and override the clone() method in the Object class.
  • Realize Serializable interface , realize cloning through object serialization and deserialization, which can realize real deep cloning.

3. What is the difference between deep copy and shallow copy?

   • Shallow clone : ​​When the object is copied, only itself and the member variables of the value type contained in it are copied, and the member objects of the reference type are not copied.
   • Deep clone : ​​In addition to the object itself is copied, all member variables contained in the object will also be copied.

Fourth, javaWeb

1. What is the difference between JSP and servlet?

   JSP is an extension of servlet technology, and is essentially a servlet-friendly way. The main difference between servlet and JSP is that the application logic of servlet is in the Java file and is completely separated from the html in the presentation layer, while in the case of JSP, Java and html can be combined into an extension called JSP document. JSP focuses on views, and servlets are mainly used for control logic.

2. What are the built-in objects of JSP? What are the functions?

  JSP has 9 built-in objects:
  • request : encapsulates the client's request, including parameters from the get or post request;
  • response : encapsulates the server's response to the client;
  • pageContext : other objects can be obtained through this object;
  • session : encapsulates The object of the user session;
  • application : the object that encapsulates the server running environment;
  • out : the output stream object that outputs the server response;
  • config : the configuration object of the Web application;
  • page : the JSP page itself (equivalent to this in the Java program) ;
  • exception : The object that encapsulates the exception thrown by the page.

3. Tell me about the four scopes of JSP?

   • page : Represents objects and properties associated with a page.
  • request : Represents objects and properties associated with a request made by the client. A request may span multiple pages and involve multiple web components; temporary data that needs to be displayed on the page can be placed in this scope.
  • session : Represents objects and attributes associated with a session established by a user with the server. Data related to a user should be placed in the user's own session.
  • application : Represents objects and properties related to the entire Web application, which is essentially a global scope that spans the entire Web application, including multiple pages, requests, and sessions.

4. What is the difference between session and cookie?

  • Different storage locations : sessions are stored on the server side; cookies are stored on the browser side.
  • Different security : cookie security is general, stored in the browser, can be forged and modified.
  • Capacity and number limit : The cookie has a capacity limit, and each site has a limit on the number of cookies.
  • Diversity of storage : Sessions can be stored in Redis, databases, and applications; while cookies can only be stored in browsers.

5. Tell me about the working principle of session?

   The working principle of session is that after the client login is completed, the server will create the corresponding session. After the session is created, it will send the session id to the client, and the client will store it in the browser. In this way, every time the client accesses the server, it will carry the sessionid. After the server gets the sessionid, it will find the corresponding session in the memory, so that it can work normally.

6. Can the session still be used if the client prohibits cookies?

   It can be used, session only relies on cookie to store sessionid, if cookie is disabled, you can use the method of adding sessionid to url to ensure that session can be used normally.

7. What is the difference between spring mvc and struts?

   • Interception level : struts2 is a class-level interception; spring mvc is a method-level interception.
   • Data independence : Spring mvc's methods are basically independent, with exclusive access to request and response data, request data is obtained through parameters, processing results are returned to the framework through ModelMap, and variables are not shared between methods; It is also independent, but all its action variables are shared, which will not affect the operation of the program, but it will bring us some trouble when coding and reading the program.
   • Interception mechanism : struts2 has its own interceptor mechanism, and spring mvc uses an independent aop method, which leads to a larger amount of configuration files in struts2 than in spring mvc.
   • Support for ajax : spring mvc integrates ajax, all ajax is very convenient to use, only one annotation @ResponseBody can be achieved; while struts2 generally needs to install plug-ins or write code by yourself.

8. How to avoid SQL injection?

   • Use preprocessing PreparedStatement.
   • Use regular expressions to filter out special characters in characters.

9. What is XSS attack and how to avoid it?

   XSS attack : Cross-site scripting attack, which is a common vulnerability in web programs. The principle is that the attacker inserts malicious script code (css code, Javascript code, etc.) into the Web page. When the user browses the page, the embedded script code will be executed, so as to achieve the purpose of maliciously attacking the user, such as stealing the user Cookies, destroying page structure, redirecting to other websites, etc.
   The core of XSS prevention is to filter the input data.

10. What is CSRF attack and how to avoid it?

   CSRF: Cross-Site Request Forgery (Chinese: Cross-Site Request Forgery), which can be understood as the attacker stealing your identity and sending malicious requests in your name, such as: sending emails, messages, purchasing goods in your name, virtual Currency transfer, etc.
   Defense means:
   • Verify the source address of the request;
   • Add a verification code to the key operation;
   • Add a token to the request address and verify it.

Summarize

  The last article introduced you to the most basic common interview questions in java in java and a summary of common interview questions in java containers. This article introduces you to multi-threading, reflection, object copying and the corresponding interview questions in javaWeb. Refer to the summary of the answers, and some of the questions give corresponding implementation cases to further prove the correctness of our answers. I hope that everyone can master it well on the basis of understanding. This is the foundation and core of java. Only when these basic knowledge are mastered can we better apply these in the actual development process. In short, whether it is an interview or a beginner, this article will be helpful to colleagues in the java direction. I hope everyone will study hard, work hard, live to old age, learn old, and continuously improve their skills. At the same time, I also hope that the friends who are looking for a job can find a satisfactory job! ! ! !

Guess you like

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