preface
Dear brothers, the Redis series will probably be stopped for the time being, as it has reached the 24th articleIn-depth understanding of Redis master-slave replicationIf you are interested, you can check out this series of articles (please feel free to like them and follow them). After that, I will sort out some things related to the interview. The main thing is that I don’t remember many things myself, so I will take this opportunity to pick them up and prepare for the end of the year. Then this is a continuous update, interested in the interview questions can be left in the comments, I will add in, not my baidu add in (dog head to protect life).
1. What are the object-oriented features of JAVA?
There are four main features: encapsulation, inheritance, polymorphism, and abstraction (many people think there are only three)
encapsulation
The idea of encapsulation ensures the integrity of the internal data structure of the class, so that users can not easily operate the internal data of the class, which reduces the impact on the internal data and improves the security and maintainability of the program. Advantages:
- Data can only be accessed through specified methods.
- Hide class number implementation details.
- Easy to modify implementation.
- Easy to add control statements.
inheritance
Inheritance is when a subclass inherits the characteristics and behavior of its parent class so that its object (instance) has the instance fields 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. Another thing to know, there’s a concept called portfolio that you can bring up in your interview. Composition is actually very simple, is simply to introduce an object into the current class, so that the current class has the function of introducing the class, because JAVA can only single inheritance, so in some scenarios, composition is actually more appropriate. Features:
- Reuse of inherited parent classes.
- Inheritance can be multi-level.
- A class can inherit only one parent class.
- In the parent class
private
Modified cannot be inherited. - Constructors cannot be inherited.
polymorphism
Polymorphism is the ability to have many different manifestations or forms of the same behavior. The resulting scene is a reference that assigns a subclass object to a parent class, resulting in polymorphism. For example :Father son = new son () The son object can only call Father’s methods (which are overridden or inherited by the child class), but cannot call some methods defined by itself. Because polymorphisms emphasize that when you write a Java program, referencing a type variable can only call a variable of its compile-time type, not its runtime type. Features:
- Reuse of inherited parent classes.
- Inheritance can be multi-level.
- A class can inherit only one parent class.
- Private modifiers in parent classes cannot be inherited.
- Constructors cannot be inherited.
Necessary: Inheritance, overwriting, parent class references to subclass objects.
Function:
- Instead of writing function calls for each subclass, you can directly treat different subclasses as parent classes, shielding differences between subclasses (or hiding details) and improving code generality/reuse.
- A parent class reference can call the functionality of different subclasses, improving the extensibility and maintainability of code.
abstract
When the abstract keyword is used to modify a class, the class is called abstract. An abstract class is a collection of common attributes of all its subclasses, and is a class that contains one or more abstract methods. However, it does not mean that there can only be abstract methods in abstract classes. It can have ordinary member variables and methods, just like ordinary classes. Features:
- Abstract classes cannot be instantiated. A subclass of an abstract class must give a concrete implementation of an abstract method in the abstract class, unless the subclass is also an abstract class.
- An abstract class does not necessarily contain abstract methods, but a class with abstract methods must be an abstract class.
- Abstract method in abstract class is only declared, does not contain the method body, is not given the concrete implementation of the method is the concrete function of the method.
- Constructor, class method (with
static
Modified methods cannot be declared as abstract methods. - Is defined as
abstract
Class needs to be inherited by subclasses, but is modified tofinal
Classes cannot be inherited or overwritten; the two cannot be used together for decoration.
2. What are the basic data types in JAVA, and what are their corresponding sizes and packaging types?
Eight basic data types: int, short, float, double, Long, Boolean, byte, char.
The encapsulation classes are Integer, Short, Float, Double, Long, Boolean, Byte, Character.
Int :4, short:2, float:4, double:8, long:8, Boolean :1, byte:1, char:2
3. What are the Java reference types?
There are four types of references, including strong reference, SoftReference, WeakReference, and virtual reference.
- Strong reference
One of the most common references. Such asString s = "abc"
, the variables
It’s a stringabc
Strong reference to. As long as the strong reference exists, the garbage collector will not reclaim the object. - Soft references (
SoftReference.java
)
Used to describe useful but not necessary objects that are not recycled if they have enough memory and are not recycled if they have enough memory. Generally used to implement memory sensitive caching, soft references can and reference queuesReferenceQueue
In conjunction, if the soft reference object is garbage collected, the JVM adds the soft reference to the reference queue associated with it. - A weak reference (
WeakReference.java
)
Weak and soft references are roughly the same, the difference being that objects with only weak references have a shorter lifetime. When the garbage collector thread scans the memory area under its control, once it finds an object with only weak references, it reclaims its memory regardless of whether the current memory space is sufficient. - Virtual reference (
PhantomReference.java
)
Unlike other references, virtual references do not determine the lifetime of the object. If an object holds only virtual references, it can be collected by the garbage collector at any time, just as if there were no references at all. Virtual references are mainly used to track the activity of objects being collected by the garbage collector.
4. What are the differences between String, StringBuffer, and StringBuilder?
String
String is immutable (its value is immutable). This results in a new String being generated for every operation on a String, which can lead to performance problems and memory overruns in scenarios where operations are frequent.
StringBuffer
A StringBuffer is a mutable class object that maintains an array of characters. Also, StringBuffer is thread-safe because all public methods of StringBuffer are synchronized modified. This can lead to performance problems in the case of large data volumes.
StringBuilder
StringBuilder and StringBuffer are the same in that they are both string variables. The difference is that none of StringBuilder’s methods add the synchronized modifier. So it’s better than StringBuffer in terms of performance, but StringBuilder is not thread-safe in multithreaded environments.
5. Can you tell me the difference between a process and a thread?
Every time I’m asked this type of question, I want to say no.
process
A process is an application that is running on the system. Once run, a program is a process, and a process is the smallest unit of resource allocation.
thread
Thread is the basic unit of the system to allocate processor time resources, is the smallest unit of program execution. Or a unit execution stream that executes independently within a process.
chestnuts
Wechat, for example, is actually a process. And like wechat circle of friends, scan and other functions can be understood as a separate thread.
6. How do you normally create threads? Is there any other way?
- By implementing
Runnable
Interface,Runnable
The implementation class creates the thread class as an argument. - Through inheritance
Thread
Class creates a thread class (overriderun
Methods). - By implementing
Callable
andFuture
Create a thread (the return value of which can be retrieved).
7. What is the difference between the start and run methods in Thread?
The start method is used to start the newly created thread, while run is generally the business logic corresponding to the thread. On the other hand, the start method calls the run method internally, which has a different effect than calling the run method directly. When you call the run method, it will only be called in the original thread. No new thread will be started, so the start method will start a new thread.
8. Have you used thread pools before? How does it work?
Yes, the frequent creation and destruction of threads increases the consumption of system resources on the one hand, and affects the performance of the program on the other. In multi-tasking scenarios, you can use pooling techniques to eliminate creation and destruction. In Java, a common thread pool is newSingleThreadExecutor(a single-threaded thread pool that only uses a single worker thread to perform tasks, Ensure that all tasks are executed in the specified order (FIFO, LIFO, priority), newFixedThreadPool(fixed length thread pool, which controls the maximum number of concurrent threads, and the exceeding threads will wait in the queue), newCachedThreadPool(cacheable thread pool, If the thread pool length exceeds processing requirements, idle threads can be recycled flexibly; if no thread pool can be recycled, new threads can be created) and newScheduledThreadPool(a thread pool with a fixed length, which supports the execution of scheduled and periodic tasks).
The principle of
The thread pool is created by specifying the default parameters of the thread pool. The thread pool is created by specifying the default parameters of the thread pool.
maximumPoolSize
Maximum number of threads.corePoolSize
Number of core threads.keepAliveTime
Thread active time.TimeUnit
Unit of time a thread is active.workQueue
Block the queue.RejectedExecutionHandler
Rejection strategy.ThreadFactory
Create a factory for threads.
Again, organize your own conversation based on your understanding of thread pools.
9. What are the thread pool rejection policies?
When the thread pool is unable to create new threads (see figure above), the thread pool implements a rejection policy. The rejection strategy mainly has the following (of course, the investigation of custom strategy, if the interviewer asked this or asked the deep more abnormal) :
AbrtPolicy
The default strategy is to simply drop the task and throw an exception.CallerRunsPolicy
Only the caller’s thread is used to process the task.DiscardOldestPolicy
Discards the oldest task in the wait queue and executes the current task.DiscardPolicy
The task is discarded without throwing an exception.
10. What are the differences between wait and sleep?
wait | sleep | |
---|---|---|
Call time | Can only be called in a synchronous context, otherwise thrownIllegalMonitorStateException abnormal |
It does not need to be called in a synchronous context |
Function object | Defined in theObject Class, acting on the object itself |
Defined in theThread Is applied to the current thread |
Release resources | Releases the lock resource when called | The current thread is blocked |
Wake up the way | callnotify ,notifyAll Or a timeout |
callinterrupt Or timeout |
The method attributes | Instance methods | A static method |
11. How does the volatile keyword work?
Using volatile declared variables in the first place ensures that values are immediately visible to other threads when they are updated and prevents instruction reordering.
The principle of
I will answer this question first, then take a look at the MESI protocol and the Java memory model. As for the principle of instruction rearrangement, I will ignore sex. Because there are too many things in this piece, it will take a long time to pull down and it is difficult to explain clearly.
The msci agreement
Multi-core CPU read/write data process is roughly CPU -> CPU cache (L1, L2, L3) -> memory, The MESI(Modified, Exclusive, Shared, Invalid) protocol is used to ensure that copies of Shared variables used in each cache are consistent with those in memory. When the CPU writes data to a shared variable, it sets the variable to its Exclusive state. When the CPU writes data to a shared variable, it sets the variable to its Modified state. The bus sniffing mechanism then signals other cpus to set the variable’s cache line to Invalid. Change the state of the variable to Shared after setting. When another CPU needs to read the variable and finds that its cache line is Invalid, it will re-read it from memory.
Principle of volatile
First of all, Java’s memory model (JMM) is basically the same as above. The JMM also distinguishes between main memory (main memory) and thread copy (cache). Changes to volatile variables force the values to be flushed to main memory. Changing a volatile variable invalidates the value of the corresponding variable in the working memory of other threads (same as above). Therefore, reading the value of this variable requires reading the value from main memory again (for visibility).
12. Can you explain the function and principle of synchronized?
Synchronized is one of the most common and easiest ways to solve concurrency problems in Java. There are three main functions of synchronized:
- Access synchronization code that ensures threads are mutually exclusive.
- Ensure that changes to shared variables are visible in a timely manner.
- Effectively solve the reorder problem.
The principle of
With synchronized, the compiled bytecode will find monitorenter and Monitorexit bytecode instructions appended to synchronized blocks and ACC_SYNCHRONIZED tokens added to synchronized methods. Each object in Java then has its own monitor lock, and the monitorenter directive (as does the ACC_SYNCHRONIZED tag execution logic) is an attempt to acquire monitor ownership. If the object is not locked or has acquired a lock (reentrancy), the lock counter is +1, at which point other threads competing for the lock are queued. The Monitorexit directive can only be executed by the thread holding the Monitor lock. When the Monitorexit directive is executed, the monitor lock’s counter does -1. When the counter value is 0, the lock is released and the threads in the wait queue are awakened to continue competing for the lock.
13. Synchronized lock optimization
Prior to JDK1.6, synchronized locks were a heavyweight lock. Synchronized locks have undergone a number of optimizations since JDK1.6. Optimization mechanisms include adaptive locking, spin locking, lock elimination, lock coarser, lightweight locking and biased locking. Synchronized locks start out as biased locks rather than heavyweight locks, and then upgrade from no-lock -> biased -> lightweight -> heavyweight locks through lock contention.
spinlocks
Spinlocks occur mainly during thread blocking waits. Since locks are held for a short time most of the time and shared variables are locked for a short time, there is no need to suspend threads, and the back-and-forth context switching between user-mode and kernels seriously affects performance. The idea of spin is to let the thread execute a busy loop, which is understood as doing nothing to prevent the transition from user to kernel mode.
Adaptive lock
Adaptive lock is an adaptive spin lock. The spin time is not fixed time, but determined by the previous spin time on the same lock and the state of the lock holder.
Lock elimination
Lock elimination is when the JVM detects synchronized blocks of code that are completely free of data contention, meaning that no lock is required and lock elimination is performed.
Lock coarsening
Lock coarsening occurs when many operations lock the same object, extending the lock synchronization beyond the entire operation sequence.
The CAS has no locking mechanism
CAS(Compare And Swap/Set) is an optimistic lock implementation, which literally means Compare And Swap/ assign. The CAS mechanism uses the basic operands of memory address V, the old expected value A, and the new value B3. When updating A variable, the value of memory address V will be changed to B only when the old expected value A and the actual value of memory address V are the same.
Biased locking
When threads access synchronized blocks access to lock in the object lock records in the head and the stack frame store thread ID, biased locking this thread enters the synchronized block again after all don’t need the CAS to lock and unlock, biased locking will bias the first thread gets the lock, if no other threads subsequent won this lock, thread holding the lock will never need to synchronize, Conversely, when there are other threads competing for the biased lock, the thread holding the biased lock will release the biased lock.
Lightweight lock
When code enters a synchronized block, the JVM will use CAS to attempt to acquire the lock. If the update succeeds, the status bit in the object header will be marked as a lightweight lock. If the update fails, the current thread will attempt to spin to acquire the lock.
Lock upgrade process
Lock upgrade process is very complex, good brothers summed up the language, as simple as possible. The following figure
14. Have you used ThreadLocal before?
This kind of question really want to return a unused, no (and then the finale)
ThreadLocal is a class that stores generic variable data. When a ThreadLocal is used to maintain variables, ThreadLocal provides a separate copy of the variable for each thread that uses the variable, so that each thread can change its own copy independently without affecting the corresponding copy of other threads. It is actually a way of isolating data (sacrificing memory space) to achieve thread-safety.
The principle of
ThreadLocal maintains a Map variable (ThreadLocalMap, not HashMap) that, when called, uses the current thread as its key. The key should be the ThreadLocal object itself, which contains the current thread, and the parameter value should be set to the static inner class Map of ThreadLocal. To do this, we use the current thread as the key and get it from ThreadLocalMap.
This issue is over here, if there is something wrong, welcome to leave a message in the comment section, and ask for attention and praise