"Preparation at the end of the year" Java Advanced Interview Questions on Java Basics (with detailed answers)

Preface

Good brothers, the Redis series of articles may not be done for now. At present, I have written the twenty-fourth in-depth understanding of Redis master-slave replication. If you are interested, you can look through this series of articles (remember to like and add Pay attention). In the following words, I will sort out some interview-related things. The main thing is that I have a lot of things I can't remember. Taking this opportunity to pick it up is also part of the year-end preparation. After that, this is continuously updated. If you are interested in interview questions, you can leave a comment in the comments. If you can, I will add it. If you don't, I will add it to Baidu (dog head saves your life).

"Preparation at the end of the year" Java Advanced Interview Questions on Java Basics (with detailed answers)

 

1. What are the object-oriented features in JAVA?

There are four main characteristics: encapsulation, inheritance, polymorphism, and abstraction (many people also think that there are only three characteristics)

Package

The encapsulation concept ensures the integrity of the internal data structure of the class, so that users cannot easily directly manipulate the internal data of the class, which reduces the impact on internal data and improves the security and maintainability of the program.
Advantages :

  1. The data can only be accessed through prescribed methods.
  2. Hidden class number implementation details.
  3. Easy to modify and realize.
  4. It is convenient to add control statements.

inherit

Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance domain and methods of the parent class, or the class inherits methods from the parent class, so that the subclass has the same behavior as the parent class.
One more thing you need to know is that there is another concept called combination , which can be mentioned during the interview. The combination is actually very simple, that is, simply introduce an object into the current class, so that the current class has the function of introducing the class. Because JAVA can only inherit from it, the combination is actually more suitable in certain scenarios.
Features :

  1. Inherit the reuse of the parent class.
  2. Inheritance can be multi-layered.
  3. A class can only inherit one parent class.
  4. The private modification in the parent class cannot be inherited.
  5. The construction method cannot be inherited.

Polymorphism

Polymorphism is the ability to have multiple different manifestations or forms of the same behavior. The resulting scene is a reference to the subclass object assigned to the parent class, which will produce polymorphism. For example: Father son = new Son() At this time, the object son can only call Father's methods (referring to those methods that the subclass overrides or inherits from the parent class), but cannot call some methods defined by itself. Because of the emphasis in polymorphism: when writing a java program, reference type variables can only call variables of their compile-time type, not their runtime type variables.
Features :

  1. Inherit the reuse of the parent class.
  2. Inheritance can be multi-layered.
  3. A class can only inherit one parent class.
  4. The private modification in the parent class cannot be inherited.
  5. The construction method cannot be inherited.

Prerequisites  : Inheritance, rewriting, parent class references point to subclass objects

Function :

  1. There is no need to write the function calls of each sub-category. You can directly treat the different sub-categories as the parent category, shielding the differences between the sub-categories (it can also be said that the details are hidden), and improving the common rate / reuse rate of the code.
  2. Parent class references can call the functions of different subclasses, which improves the scalability and maintainability of the code.

abstract

When using the abstract keyword to modify a class, the class is called an abstract class. An abstract class is a collection of common attributes of all its subclasses, and is a class that contains one or more abstract methods. But it doesn't mean that there can only be abstract methods in an abstract class. It can have ordinary member variables and methods just like ordinary classes.
Features :

  1. Abstract classes cannot be instantiated. A subclass of an abstract class must give concrete implementations of abstract methods in the abstract class, unless the subclass is also an abstract class.
  2. Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.
  3. The abstract method in the abstract class is just a declaration, and does not contain the method body, that is, the specific implementation of the method is not given, that is, the specific function of the method.
  4. Construction methods, class methods (methods modified with static) cannot be declared as abstract methods.
  5. The class defined as abstract needs to be inherited by subclasses, but the class modified as final cannot be inherited or rewritten, and the two cannot be used together for modification.

2. What are the basic data types in JAVA, and what are the corresponding sizes and packaging types?

Eight basic data types: int, short, float, double, long, boolean, byte, char.

The package classes are: Integer, Short, Float, Double, Long, Boolean, Byte, Character.

The sizes are (byte): int:4, short:2, float:4, double:8, long:8, boolean:1, byte:1, char:2.

3. What are the reference types in Java?

There are four kinds of references, namely strong reference, soft reference (SoftReference), weak reference (WeakReference), and phantom reference (PhantomReference).

  1. Strong citation The
    most common citation method. For example, String s = "abc", the variable s is a strong reference to the string abc. As long as the strong reference exists, the garbage collector will not reclaim the object.
  2. Soft reference (SoftReference.java) is
    used to describe objects that are still useful but not necessary. If the memory is enough, it will not be recycled, and if the memory is insufficient, it will be recycled. Generally used to implement memory-sensitive caches, soft references can be used in conjunction with ReferenceQueue. If the soft referenced object is garbage collected, the JVM will add the soft reference to the reference queue associated with it.
  3. Weak reference (WeakReference.java)
    Weak reference and soft reference are roughly the same. The difference between weak reference and soft reference is that only objects with weak references have a shorter life cycle. In the process of the garbage collector thread scanning the memory area under its jurisdiction, once an object with only weak references is found, its memory will be reclaimed regardless of whether the current memory space is sufficient.
  4. Phantom Reference (PhantomReference.java)
    is the same as fictitious, different from other kinds of references. Phantom reference does not determine the life cycle of the object. If an object holds only phantom references, then it is the same as without any references, and may be collected by the garbage collector at any time. Phantom references are mainly used to track the activities of objects being recycled by the garbage collector.

4. What are the differences between String, StringBuffer and StringBuilder?

String

String is an immutable (immutable value) class object, which leads to a new String object generated every time a String is operated on, and performance problems and memory overflow may occur in scenes with frequent operations.

StringBuffer

StringBuffer is a variable-valued class object, which is maintained internally by a character array. In addition, StringBuffer is thread-safe, because all public methods of StringBuffer are modified by synchronized. This will also lead to performance problems when the amount of data is large.

StringBuilder

StringBuilder and StringBuffer are the same, both are string variables. The difference is that the methods of StringBuilder are not modified with synchronized. So it is better than StringBuffer in performance, but StringBuilder is not thread-safe in a multithreaded environment.

5. Can you talk about the difference between process and thread?

Every time I ask someone who can talk about this type of question, I really want to say no.

process

A process refers to an application program that is running in the system. Once a program runs, it is a process, and the process is the smallest unit of resource allocation.

Thread

Thread is the basic unit for the system to allocate processor time resources and the smallest unit of program execution. In other words, a unit execution flow that executes independently within a process.

chestnut

For example, WeChat that we usually use is actually a process. And functions like WeChat Moments and Scan can be understood as separate threads.

6. How do you usually create threads, and are there other ways?

  1. Create a thread class by implementing the Runnable interface and taking the Runnable implementation class as a parameter.
  2. Create a thread class by inheriting the Thread class (override the run method).
  3. Create a thread by implementing Callable and Future (you can get the return value of the thread).

7. What is the difference between the start and run methods in the Thread class?

The start method is used to start a newly created thread, and run is generally the business logic corresponding to the thread.
On the other hand, the run method is called inside the start method, which is different from the effect of calling the run method directly. When you call the run method, it will only be called in the original thread. If no new thread is started, the start method will start the new thread.

8. Have you used the thread pool and what is the principle?

Used, because the frequent creation and destruction of threads will increase the consumption of system resources on the one hand, on the other hand, it will affect the performance of the program. In multitasking scenarios, pooling technology can be used to omit the process of creation and destruction. In Java, the common thread pools are newSingleThreadExecutor (single-threaded thread pool, it will only use a single worker thread to perform tasks, to ensure that all tasks are executed in the specified order (FIFO, LIFO, priority)), newFixedThreadPool (fixed Long thread pool, which can control the maximum concurrent number of threads, and the excess threads will wait in the queue), newCachedThreadPool (a cacheable thread pool, if the length of the thread pool exceeds the processing needs, the idle thread can be flexibly recycled, if there is no recyclable, then a new thread ), newScheduledThreadPool (fixed-length thread pool, supports timing and periodic task execution).

principle

In this case, I personally think that it is enough to explain the execution process of the entire thread pool. Of course, you can first talk about the seven parameters of the thread pool that creates the thread pool (the above several commonly used thread pools are also by specifying the default parameters. Created).

  1. maximumPoolSize The maximum number of threads.
  2. corePoolSize The number of core threads.
  3. KeepAliveTime thread active time.
  4. TimeUnit thread active time unit.
  5. The workQueue blocks the queue.
  6. RejectedExecutionHandler reject strategy.
  7. ThreadFactory creates a factory for threads.

Still the same, organize the words based on the understanding of the thread pool.

"Preparation at the end of the year" Java Advanced Interview Questions on Java Basics (with detailed answers)

 

9. What are the rejection strategies of the thread pool?

When the thread pool can no longer innovate threads (refer to the figure above), the thread pool will implement the rejection strategy. The main rejection strategies are as follows (of course, check for custom strategies. If an interviewer asks this, the question is deeper and more abnormal):

  1. AbrtPolicy directly discards tasks and throws exceptions. This is the default policy.
  2. CallerRunsPolicy only uses the thread of the caller to process tasks.
  3. DiscardOldestPolicy discards the oldest task in the waiting queue and executes the current task.
  4. DiscardPolicy directly discards tasks without throwing exceptions.

10. Briefly talk about the difference between wait and sleep?

The waitsleep call timing can only be called in the synchronization context, otherwise it is not necessary to call the IllegalMonitorStateException in the synchronization context. The object is defined in the Object class, and the object itself is defined in the Thread, and the current thread is released when the resource is called. The lock resource is adjusted and the resource is not released, and the current thread is blocked. The wake-up method calls notify, notifyAll, or calls the interrupt or timeout method. Static method.

11. Have you understood the principle of the volatile keyword?

The first use of volatile declared variables can ensure that the value is immediately visible to other threads when the value is updated, and can prevent instruction reordering.

principle

For this question, I will answer the above role first, and then I will look at the MESI protocol and the Java memory model. As for the principle of instruction rearrangement, I will ignore it. Because this piece is too much, it will take a long time to pull it off and it will be more difficult to explain clearly.

MESI agreement

The process of multi-core CPU reading/writing data is roughly CPU -> CPU cache (L1, L2, L3) -> memory, MESI (Modified, Exclusive, Shared, Invalid acronym) protocol is used to ensure that each The copy of the shared variable used in the cache is consistent with the memory. When the CPU writes data, if it finds that the manipulated variable is a shared variable, first set the variable to the Exclusive state, when the setting operation is to set the variable state to the Modified state, and then send it through the bus sniffing mechanism Signals other CPUs to set the cache line of this variable to an invalid (Invalid) state. After setting, change the variable status to Shared. When other CPUs need to read this variable, they will find that the cache line that caches the variable in their cache is invalid (Invalid), and then it will reread it from the memory.

"Preparation at the end of the year" Java Advanced Interview Questions on Java Basics (with detailed answers)

 

Volatile principle

First of all, Java's memory model (JMM) is the same as the basic idea above. In JMM, the main memory (main memory) and thread copy (cache) are also distinguished. When a volatile variable is modified, the modified value will be forced to refresh the main memory. Modifying a volatile variable will cause the corresponding variable value in the working memory of other threads to become invalid (consistent with the above). Therefore, when the variable value is read again, the value in the main memory needs to be read again (to ensure visibility).

12. Can you talk about the role and principle of synchronized?

Synchronized is one of the most commonly used methods to solve concurrency problems in Java, and it is also the simplest method. There are three main functions of synchronized:

  1. Ensure that threads are mutually exclusive to access synchronization code.
  2. Ensure that the modification of shared variables can be seen in time.
  3. Effectively solve the reordering problem.

principle

After using synchronized, the compiled bytecode will find that the monitorenter and monitorexit bytecode instructions will be added before and after the synchronized code block, and the ACC_SYNCHRONIZED mark will be added in the synchronization method. Then in Java, each object will have its own monitor lock (monitor). When the monitorenter instruction is executed (the ACC_SYNCHRONIZED flag execution logic is the same), it is the process of trying to obtain the ownership of the monitor. If the object is not locked or the lock has been acquired (reentrancy), the lock counter is +1, and other threads competing for the lock will enter the waiting queue.
The monitorexit instruction can only be executed by the thread holding the monitor lock. When the monitorexit instruction is executed, the counter of the monitor lock will do -1 operation. When the counter value is 0, the lock is released, and threads in the waiting queue are awakened to continue competing for the lock.

13. Have you learned about synchronized lock optimization?

Before the JDK1.6 version, the synchronized lock was a heavyweight lock. Since the JDK1.6 version, a series of optimizations have been made to the synchronized lock. Optimization mechanisms include adaptive locks, spin locks, lock elimination, lock coarsening, lightweight locks, and bias locks. To put it simply, using synchronized locks will initially become biased locks instead of heavyweight locks, and then after lock competition, there will be a lock upgrade process from no locks -> biased locks -> lightweight locks -> heavyweight locks. .

Spin lock

Spin locks mainly occur during thread blocking and waiting. Because most of the time the lock is occupied for a short time, the lock time of shared variables is also very short. There is no need to suspend the thread. The context switch between user mode and kernel mode has a serious impact performance. The concept of spin is to let the thread execute a slow loop, which can be understood as doing nothing to prevent the transition from user mode to kernel mode.

Adaptive lock

An adaptive lock is an adaptive spin lock. The spin time is not a fixed time, but is determined by the previous spin time on the same lock and the state of the lock holder.

Lock elimination

Lock elimination means that the JVM detects some synchronized code blocks, and there is no data contention scenario at all, that is, lock elimination will be performed without locking.

Chain coarsening

Lock coarsening means that there are many operations that lock the same object, which will extend the synchronization range of the lock beyond the entire sequence of operations.

CAS no lock mechanism

CAS (Compare And Swap/Set) is an implementation of optimistic locking, which literally means compare and swap/assign. The CAS mechanism uses three basic operands: the memory address V, the old expected value A, and the new value B to be modified. When updating a variable, only when the old expected value A and the actual value in the memory address V are the same, Then the value corresponding to the memory address V is changed to B.

Bias lock

When a thread accesses a synchronization block to acquire a lock, it will store the thread ID of the biased lock in the lock record in the object header and stack frame. After this thread enters the synchronization block again, it does not require CAS to lock and unlock. The biased lock will Always prefer the first thread that obtains the lock. If no other threads subsequently obtain the lock, the thread holding the lock will never need to synchronize. Conversely, when other threads compete for the lock, the thread holding the lock will be Will release the bias lock.

Lightweight lock

The object header of the JVM object contains some lock flags. When the code enters the synchronization block, the JVM will use the CAS method to try to acquire the lock. If the update is successful, the status bit in the object header will be marked as lightweight Lock, if the update fails, the current thread tries to spin to obtain the lock.

Lock upgrade process

The process of lock upgrade is very complicated. Good brothers sum up the language by themselves and try to be simple. As shown below

"Preparation at the end of the year" Java Advanced Interview Questions on Java Basics (with detailed answers)

 

14. Have you ever used ThreadLocal? Have you understood the principle?

This kind of question really wants to return to a never used one, no (then the finale)

First of all, ThreadLocal is a storage generic variable data class. When using ThreadLocal to maintain variables, ThreadLocal provides an independent variable copy for each thread that uses the variable, so each thread can change its own copy independently without affecting Corresponding copies of other threads. In fact, it is a way of data isolation (sacrificing memory space) to achieve thread safety.

principle

This is relatively simple. In fact, ThreadLocal maintains a Map variable (ThreadLocalMap, not HashMap) internally. When the set method is called, the current thread will be used as the key (actually this is not so accurate, it should be the ThreadLocal object itself as key, the ThreadLocal object contains the current thread), the parameter is used as the value, and then set to the static internal class Map (ThreadLocalMap) of ThreadLocal. The value is to use the current thread as the key and get it from ThreadLocalMap.

This is the end of this issue. If there is something wrong, please leave a message in the comment area, and ask for attention and praise

Guess you like

Origin blog.csdn.net/a159357445566/article/details/112199238