Effortless JAVA Interview Success_2021 Latest Edition

 

I changed my job at the end of 2020. During this period, I went to major companies for interviews. Before the interview, I searched the Internet for the latest java interview collections and 100 java written test questions. I was full of confidence during the interview and I was finishing several companies. After answering the java written test questions and answering the interview questions of the interviewer, I found that although the previous interview preparation took a lot of effort, the interview results were not satisfactory. After experiencing several setbacks, I finally succeeded in getting an offer from my favorite unit. My previous personal experience is really a bloody lesson! A set of the latest version of java interview test sites in 2021 will help you to finish the java interview effortlessly. Now I am conscientiously sorting out the work for later reference. Find out the following test sites and passing the written test interview should not be a big problem. The dry goods are now presented as follows, encourage!

I have compiled an interview book, friends in need, click here to get it for free!

This year's test center focused on: threads, concurrency, and the source code and architecture of popular frameworks.

1) What is a process?
A process is an executing application, and a thread is an execution sequence within the process. A process can have multiple threads. Threads are also called lightweight processes.

2) What is a thread?
Threads are a subset of processes. A process can have many threads, and each thread performs different tasks in parallel. Different processes use different memory spaces, and all threads share the same memory space.

3) Java has three ways to create threads

  • Java does not support multiple inheritance of classes, but allows you to call multiple interfaces
    1. Inherit the simplest new method of the Thread class, inherit a thread class
    2. Implement the Runnable interface When you need to inherit the functions of other classes, choose the runnable interface
    3. Use Framework programs can use the Executor framework to create a thread pool, the thread pool can limit the number of threads and can recycle these threads

4) A general explanation of the following states of threads during execution, pay attention to understand the differences between them.

 
  1. Ready (Runnable): The thread is ready to run and may not be able to start execution immediately.
  2. Running: The process is executing the code of the thread.
  3. Waiting: The thread is in a blocked state, waiting for the external processing to end.
  4. Sleeping: The thread is forced to sleep.
  5. I/O blocked (Blocked on I/O): Waiting for the completion of the I/O operation.
  6. Blocked on Synchronization: Waiting to acquire a lock.
  7. Dead: The thread has completed its execution.

5) How to create a daemon thread?
Use the setDaemon(true) method of the Thread class to set the thread as a daemon thread. It should be noted that this method needs to be called before calling the start() method, otherwise an IllegalThreadStateException will be thrown.

6) What is the difference between user thread and daemon thread (Daemon thread)?
When we create a thread in a Java program, it is called a user thread. A daemon thread is a thread that executes in the background and does not prevent the JVM from terminating. When no user threads are running, the JVM closes the program and exits. Child threads created by a daemon thread are still daemon threads.
The daemon process can be terminated and exited by the jvm, and the user process cannot be terminated by the jvm.
The daemon thread refers to the thread that provides a general service in the background when the program is running, and this thread is not an indispensable part of the program.

7) How to ensure thread safety?
There are many ways to ensure thread safety in Java-synchronization, use atomic concurrent classes, implement concurrent locks, use the volatile keyword, use immutable classes and thread-safe classes.


Everyone is familiar with the synchronized synchronized block, which is realized by the synchronized keyword; all the methods and block statements with synchronized can only be accessed by one thread at the same time during multi-threaded access.
The volatile keyword
volatile is a special modifier, and only member variables can use it. In the absence of synchronization classes in Java concurrent programs, the operations on member variables by multiple threads are transparent to other threads. Volatile variables can guarantee that the next read operation will occur after the previous write operation. Threads will read the variable directly from memory and do not cache it. This ensures that the variable read by the thread is consistent with the memory.
ThreadLocal variable
ThreadLocal is a special kind of variable in Java. Each thread has a ThreadLocal, that is, each thread has its own independent variable, and the race condition is completely eliminated. If each thread is provided with its own unique variable copy, it will greatly improve efficiency. First, the number of costly objects created is reduced through reuse. Second, you gain thread safety without using expensive synchronization or immutability.

8) The difference between thread sleep and wait

Sleep means that the thread enters the dormant state, keeps the object lock, and only releases the cpu.
Wait means that the thread is in the waiting state, the object lock is released, and the cpu is released.
sleep (100L) means: keep the object lock, the thread sleeps for 100 milliseconds,
wait (100L) means: release the object lock, the thread waits for 100 milliseconds.
The difference is that the sleep method is a method in the Thread class, and the lock is not released when it is called; the wait method is a method in the Object class, and the lock is released when it is called.

Both wait and sleep in Java programs will cause some form of pause, and they can meet different needs. The wait() method is used for inter-thread communication. If the waiting condition is true and other threads are awakened, it will release the lock. 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. It should be noted that sleep() does not terminate the thread. Once the thread is awakened from sleep, the thread's state will be changed to Runnable, and it will be executed according to thread scheduling.

9) What is the difference between the start() and run() methods in the Thread class?

The start() method is used to start the newly created thread and make the state of the created thread become runnable.
When you call the run() method, no new thread is started, it will only be called in the original thread. This method is the same as the run method of a normal class.

  1. What is the difference between Runnable and Callable in Java?
    Runnable: It has been available since JDK1.0, but the run() method of Runnable did not return a result.
    Callable was added in JDK1.5. Not only execution, Callable's call() method can return values ​​and throw exceptions, and can also return Future objects loaded with calculation results.

11) Deadlock
Multithreading, resource competition, illegal process advancement program, (cyclic waiting).
Treatment strategy: ostrich strategy, prevention strategy, avoidance strategy, detection and recovery strategy

  1. The difference between int and integer
    1) int is a basic data type, and integer is a package class of int (reference type)

  2. The initial values ​​of the member variables of the class are different, one is 0 and the other is null.
    3) When assigning directly, int=10 and integer=10 are the same in the range of [-128-127].
    4) When there is a new integer value, the reference address is stored in the object, so it cannot be compared directly with ==, and the method equals of the encapsulation class should be used to judge.
    Integer data type length: byte (8bits), short (16bits), int (32bits), long (64bits), regardless of platform.

  3. The difference between String class and StringBuffer class stringbuffer
    differs from string in that it is mostly used to process dynamic characters, adding or deleting characters.
    StringBuilder: thread-unsafe, fast, suitable for single thread
    StringBuffer: thread-safe, slow, suitable for multi-thread

14) What is the difference between & and &&?
& Is a bitwise operator, which means bitwise AND operation, && is a logical operator, which means logical and (and).

15) The difference between abstract class and interface
Abstract class is an abstraction of a class, it can have its own member variables and concrete method implementation; while an interface is an abstraction of behavior, there is no concrete realization method, mainly regarded as the realization of multiple inheritance .

16) Java memory management (jvm optimization)

[Heap, stack, method area, program calculator]

 

image_thumb_1.png

 

java.jpg

 

Untitled.jpg

JVM divides memory into: heap memory, stack memory
or: young generations, old generations, permanent generations.
Heap memory: young generation and old generation.
The new generation is to store newly created objects. If the object is not reclaimed by gc, it will enter the old generation.

17) gc garbage collection

Significance: The JVM system thread automatically performs garbage collection gc, which can release useless objects and clear memory record fragments.
Garbage collection algorithm: (1) find useless information objects; (2) reclaim the memory space occupied by useless objects, so that the space can be used again by the program.
Garbage collection algorithms can be divided into three categories, all based on mark-sweep (copy) algorithms: Serial algorithm (single thread), parallel algorithm, and concurrent algorithm.
The programmer can submit a request to clean up the garbage
through the ** System.gc() method , and the jvm itself determines whether to recycle. ** Reduce GC overhead
 (1) Don't explicitly call System.gc()
 (2) Minimize the use of temporary objects
 (3) Try to use StringBuffer instead of String to accumulate strings
 (4) Try to minimize static object variables

  1. The difference between memory leak and out of memory
  • Memory overflow: When the program is applying for memory, there is not enough memory space for it to use, and out of memory appears; for example, when an integer is applied for but a long can be stored in it, it is a memory overflow.
    When does jvm throw OutOfMemoryException: it is not thrown when the memory is emptied
    1) 98% of JVM time is spent in memory recovery
    2) Each time the memory recovered is less than 2%

  • Memory leak: It means that the program cannot release the allocated 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.
    Or [There are reachable and useless objects in the memory, and they will not be reclaimed by the GC, and they have been occupying memory.
    The object is the object of the memory leak]

  • Leaks emphasize that they cannot be recovered and occupy memory; overflow emphasizes not enough to satisfy.

  1. Common solutions to memory overflow The
    first OutOfMemoryError: PermGen space
    Permanent Generation space is not enough.
    JAVA_OPTS=" -XX:PermSize=64M -XX:MaxPermSize=128m"
    can increase the parameter size in the java virtual machine.
    The second type of OutOfMemoryError: Java heap space
    checks whether the program has redundant objects, adjusts the parameters, and increases the size of the Xms (initial heap size) and Xmx (maximum heap size) parameters in the Java virtual machine. set JAVA_OPTS= -Xms256m -Xmx1024m.

20) How to monitor the memory of
tomcat Tomcat is run through java. After checking the corresponding pid, you can use the monitoring tools
jstat and jconsole that come with jvm to view the contents of heap memory and non-heap memory in memory.

21) How to implement a servlet?

  • Implement the Servlet interface * Inherit the GenericServlet class * Inherit the HttpServlet class
    Create a custom servlet class to implement the servlet interface in java. This interface contains 5 methods.
    Or inherit the GenericServlet class or inherit the HttpServlet class.
  1. The Servlet life cycle is
    divided into three phases:
      1. The init() method is called in the initialization phase. The
      service() method is called in the response to the client request. The
      destroy() method is called in the termination phase.

23) What technologies are there to implement each part of MVC? How to implement it?
MVC is an acronym for three words, namely: Model, View and Controller. The purpose of the MVC pattern is to realize the division of functions of the Web system. The Model layer realizes the business logic in the system, which can usually be realized with JavaBean or EJB. The View layer is used to interact with the user, usually implemented with JSP, freemarker velocity. The Controller layer is the communication bridge between the Model and the View. It can dispatch user requests and select the appropriate view for display. At the same time, it can also interpret user input and map them into operations that can be performed by the model layer. Use Servlet to achieve.

24) Java concurrency
An important reason
for concurrency is to improve execution efficiency. In order to achieve concurrency, the operating system level provides multiple processes.
There is also a relatively lightweight concurrent implementation that uses threads, and a process can contain multiple threads. Multithreading is supported in the Java language.

25) Thread cooperation
Thread communication: The following 3 methods can only be called in the synchronization block.
Wait() makes the thread go to sleep.
notify() will randomly wake up a waiting thread, and it will get a chance to grab the lock. notifyAll() wake up All waiting threads

26) Deadlock [Deadlock has four necessary conditions, breaking one can remove the deadlock]
Four necessary conditions:
mutually exclusive conditions. A resource can only be used by one process at a time.
Request and hold conditions: When a thread is blocked by requesting resources, it keeps on holding the acquired resources.
Non-deprivation conditions: the resources that the thread has acquired cannot be deprived forcibly before they are used up.
Circular waiting condition: A kind of circular waiting resource relationship is formed between several threads.

 

Guess you like

Origin blog.csdn.net/m0_46995061/article/details/112845323