当前位置:网站首页>Summary of classic interview questions
Summary of classic interview questions
2022-06-11 07:25:00 【Cheng Yong UESTC】
One 、Java Class loading process
One java File from the completion of coding to the final execution , Generally, there are two processes :
- compile : What will be written Java file , adopt javac Commands are compiled into bytecode , namely .class file
- function : Will compile the generated .class Documents to JVM perform
Class loading process :JVM hold .class Class information in the file is loaded into memory , And parse to generate the corresponding class Object procedure .JVM Not all classes are loaded into memory at the beginning , Instead, only the first encounter with a class that needs to be run will load , And only load once .
Class loading is divided into three parts : load 、 Linking and initialization . The links are divided into three parts : verification 、 Preparation and analysis .
1. load . Load bytecode file into memory through classloader . Class loaders generally include : Start the class to load its 、 Extend the classloader 、 Application class loader and custom class loader .
2. verification : It is mainly to ensure that the byte stream loaded in conforms to the virtual machine specification , It will not cause safety problems . Including the verification of file format 、 Validation of metadata 、 Verification of bytecode, etc .
3. Get ready : Class variables ( It's not an instance variable ) Allocate memory and assign initial value . This initial value is not the initialization value specified in the code , It is JVM According to the default initial value of different variable types . for example :8 The default initial value of the basic type in is 0, The initial value of the reference type is null etc. .
4. analysis : The process of replacing a symbolic reference in a constant pool with a direct reference . A direct reference can be understood as a memory address , For example, calling a method hello(), Where the symbol is quoted as hello, The method address is 1234567, be 1234567 It's a direct reference to .JVM Will put all the class names 、 Method name and field name are replaced by specific memory address .
5. initialization : Initialization of class variables , Execution class constructor . let me put it another way , Only right static Decorated variable statements to initialize . If a class is initialized without its parent class initialized , Initializes its parent class first ; If it contains multiple static variables and static code blocks at the same time , Then execute from top to bottom .
Two 、JVM Memory partition

Method area : Used to save the class meta information that has been loaded by the virtual machine ( Including the version of the class 、 Field 、 Method 、 Interface, parent class and other information )、 Runtime constant information (static、final Defined constant )、 String constant information (String a=“dfc”).
3、 ... and 、Java Thread pool
Thread pool function :
- Reduce the overhead of creating and destroying threads
- Improve response time . When the mission arrives , Instead of manually creating a thread , Get the thread directly from the thread pool , It's a lot faster
- Improve thread manageability . Threads are scarce resources , If unlimited creation , Will consume system resources . Use thread pool for unified allocation 、 Tune and monitor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
- corePoolSize: Maximum number of core threads , Generally speaking, it's , The maximum number of resident threads in the thread pool
- maximumPoolSize: The maximum number of threads running in the thread pool ( Including core thread and non core thread )
- keepAliveTime: Idle threads in the thread pool ( Applies only to non core threads ) The longest time you can survive
- unit: Unit of time to live , And keepAliveTime Use it with
- workQueue: The blocking queue that holds the task ( Priority queue , be based on array Or the blocking queue implemented by the linked list, etc )
- handler: Thread pool saturation strategy

Thread pool types and applicable scenarios ( Use Executors. The following methods can easily create various types of thread pools ):
- newFixedThreadPool: There are only core threads in the thread pool , A thread pool with a fixed number of threads , When the thread is idle , They won't be recycled , Unless the thread pool is closed . When all threads are active , New tasks will be waiting , Until a thread is free . Apply to the handling of CPU Intensive tasks , Make sure CPU In the case of being used by worker thread for a long time , Allocate as few threads as possible , That is, to carry out long-term tasks .
- newSingleThreadExecutor: It is applicable to the scenario of serial execution of tasks . When there are no threads in the thread pool , A new thread will be created to execute the task ; There is a thread in the current thread pool , Add new tasks to LinkedBlockingQueue
- newCachedThreadPool: The number of core threads is 0, The threshold for the total number of threads is Integer.MAX_VALUE, That is, you can create unlimited non core threads . A new mission , If there is no idle thread, create a new thread to process the task ; If a thread in the thread pool exceeds 60s Nothing to do , The thread will be destroyed . Suitable for performing a large number of short life cycle tasks
- newScheduledThreadPool: The threshold for the total number of threads is Integer.MAX_VALUE, Work queues use DelayedWorkQueue, The survival time of non core threads is 0, Therefore, the thread pool contains only a fixed number of core threads . Two ways to submit tasks :scheduleAtFixedRate: Execute at a fixed rate cycle ;scheduleWithFixedDelay: The last task is executed after a fixed delay . It is applicable to periodic tasks , And you need to limit the number of threads
Will the thread pool using unbounded queues cause memory explosion ?
It will be ,newFixedThreadPool Using an unbounded blocking queue LinkedBlockingQueue, If the thread gets a task , The execution time of the task is relatively long , This will cause the queue to accumulate more tasks , This causes the memory usage of the machine to soar , Eventually lead to OOM.
Why not recommend Executors The following is a convenient way to create a thread pool , But directly ThreadPoolExecutor Construction method of ?
Executors A shortcut to creating a thread pool in , It's actually called ThreadPoolExecutor Construction method of ( Timed tasks use ScheduledThreadPoolExecutor):
// Java Full constructor for thread pool
public ThreadPoolExecutor(
int corePoolSize, // The number of threads that the thread pool maintains for a long time , Even if the thread is in Idle state , It won't recycle .
int maximumPoolSize, // The maximum number of threads
long keepAliveTime, TimeUnit unit, // exceed corePoolSize The thread of idle Duration ,
// Beyond that time , Extra threads will be recycled .
BlockingQueue<Runnable> workQueue, // Queuing of tasks
ThreadFactory threadFactory, // How new threads are generated
RejectedExecutionHandler handler) // Refusal strategy
Improper setting of these parameters will cause the following problems :
corePoolSizeandmaximumPoolSizeImproper setting will affect efficiency , Even running out of threads ;workQueueImproper setting can easily lead to OOM;handlerImproper setting will cause an exception to be thrown when the task is submitted .
Something to watch out for :
- Avoid using unbounded queues
- The act of explicitly rejecting a task ( Execute when the task queue is full )

// Java Full constructor for thread pool
public ThreadPoolExecutor(
int corePoolSize, // The number of formal workers
int maximumPoolSize, // The maximum number of workers , Including regular workers and temporary workers
long keepAliveTime, TimeUnit unit, // The longest idle time of temporary workers , Beyond that time you will be fired
BlockingQueue<Runnable> workQueue, // Scheduling queues
ThreadFactory threadFactory, // Recruitment channels
RejectedExecutionHandler handler) // Rejection method
Four 、linux Check whether a port is occupied
netsat -tunlpUsed for display tcp,udp Port, process, etc ,netstat -tunlp | grep Port numberlsof -i: Port number
5、 ... and 、redis colony
1、 A master-slave mode
One master, many followers , The client reads and writes to the primary database , Read from the database , The data written from the master database will be automatically synchronized to the slave database in real time . The working mechanism is :
- slave After starting , towards master send out SYNC command ,master Received SYNC Pass after command bgsave Save snapshots ( That is, the RDB Persistence ), And use the buffer to record the write commands executed during the snapshot
- master Send the saved snapshot file to slave, And continue to record the executed write commands
- slave After receiving the snapshot file , Load the snapshot file , Load data
- master Start sending snapshots to slave Send write command to buffer ,slave Receive commands and execute , Complete replication initialization
- thereafter master Every time a write command is executed, it will be sent to slave, keep master And slave Data consistency between
2、 Sentinel mode
Sentinel mode is based on master-slave mode , Only sentinels are introduced to monitor and automatically handle faults . The sentinel functions are as follows :
- monitor master、slave Is it working
- When master Failure time , Can automatically send a slave Convert to master
- Multiple sentinels monitor the same redis, Sentinels can also monitor each other
advantage : Sentinel mode is based on master-slave replication mode , There are advantages of copying from master to master , Sentinel mode also has ; In sentinel mode ,master If you hang up, you can switch automatically , Higher system availability
shortcoming : It also inherits the shortcoming that the master-slave mode is difficult to expand online ,Redis The capacity of is limited by a single machine configuration ; Additional resources are needed to start sentinel process , The implementation is a little more complicated , meanwhile slave Nodes as backup nodes do not provide services
3、 Cluster pattern
Sentinel mode solves the problem that master-slave replication cannot fail over automatically , The problem of not reaching high availability , However, it is still difficult to expand online ,Redis The capacity is limited by the single machine configuration .Cluster The pattern implements Redis Distributed storage , Each node stores different content , To solve the problem of online expansion .
The cluster mode adopts a centerless structure , Characteristic is :
- all redis Nodes interconnect with each other
- Node fail It only takes effect when more than half of the nodes in the cluster are detected to have failed
- The client and redis Node is directly connected , No intermediate agent is needed . The client can connect to any available node in the cluster
Working mechanism of cluster mode :
- stay Redis On every node of , They all have a slot (slot), The value range is 0-16383
- When we access key When ,Redis Will be based on CRC16 The result of this algorithm is , Then get the result right 16384 Mod , So each of them key They all have a number in 0-16383 The Hashi trough between , By this value , Go to find the node corresponding to the corresponding slot , Then directly and automatically jump to the corresponding node for access operation
- To ensure high availability ,Cluster Mode also introduces master-slave replication mode , A master node corresponds to one or more slave nodes , When the primary node goes down , The slave node will be enabled
Cluster Minimum configuration mode of cluster nodes 6 Nodes (3 Lord 3 from , Because it takes more than half ), The master node provides read and write operations , Slave as standby , Don't offer requests , For failover purposes only .
advantage : It can be linearly extended to 1000 Multiple nodes , Nodes can be added or removed dynamically
shortcoming :slave act as “ Cold standby ”, Can't relieve reading pressure
6、 ... and 、Java Abnormal system

- Abnormal operation period , Also called non check exception . For example, the common NullPointerException、IndexOutOfBoundsException wait . For runtime exceptions ,java The compiler does not require exception capture or throw declarations , It's up to the programmer .
- checked exception, That is, compilation exception .java The compiler forces the programmer to do capture processing , For example, the common IOExeption and SQLException. For non runtime exceptions, if you do not catch or throw a declaration , The compiler won't pass .
7、 ... and 、synchronized Lock escalation
stay Java SE 1.6 in **, There's a lock 4 States , The order of rank from low to high is :** No lock state 、 Biased lock state 、 Lightweight lock state and heavyweight lock state , These States will escalate with the competition . Locks can be upgraded but not degraded , It means that biased lock cannot be downgraded to biased lock after upgrading to lightweight lock .
Biased locking :
- Threads 1 When getting the lock object , Will be in java Record biased locks in object headers and stack frames threadID
- Threads 1 When acquiring the lock , Compare threadID Is it consistent ------- Agreement -> Direct access without the use of CAS Lock it up 、 Unlock
- Threads 2 When acquiring the lock , Compare threadID Is it consistent ------- atypism -> Check the object's threadID Whether the thread is still alive
- Survive : Represents that the object is being contested by multiple threads , So it was upgraded to a lightweight lock
- Not alive : Reset the lock to the unlocked state , The lock relabels the thread 2 For the new threadID
- If the thread 1 And thread 2 The execution time of is just staggered , Then the lock will only switch between biased locks and will not be upgraded to lightweight locks , In the use of synchronized It avoids the cost of acquiring locks , So the efficiency is very close to the unlocked state
Lightweight lock : When an object is contested by multiple threads , The lock is upgraded from biased lock to lightweight lock , The lightweight lock uses spin +CAS Way to continuously acquire locks
Heavyweight lock : When the thread spins too many times, it still fails to acquire the lock , To avoid CPU Unprovoked consumption , The lock is upgraded from a lightweight lock to a heavyweight lock .
边栏推荐
- CRMEB/V4.4标准版打通版商城源码小程序公众号H5+App商城源码
- 1300. the array closest to the target value after transforming the array and
- 2、 User login and registration
- [STL source code analysis] summary notes (9): set/multiset and map/multimap
- 模块化笔记
- es5和es6的学习小记
- 【CF#223 (Div. 2)】A. Sereja and Dima
- Education expert wangzhongze shared his experience for many years: family education is not a vassal
- 1442. number of triples forming two exclusive or equal arrays
- Notes on learning Es5 and ES6
猜你喜欢

matplotlib的cmap

@Jsonproperty annotation
![[并发进阶]——线程池总结](/img/69/dc8146dafc30f8a8efa012b67aa05c.png)
[并发进阶]——线程池总结

Installation de SQL Server 2008 (avec mot de passe), création d'une base de données, test de projet de formulaire C

The gap between the parent box and the child box

Leetcode-141. Linked List Cycle

Software testing weekly (issue 75): only when you look down, can you see your true self.

Modular notes
![[deploy private warehouse based on harbor] 4 push image to harbor](/img/af/8e28b229d94f3e6eab02308b69dc74.jpg)
[deploy private warehouse based on harbor] 4 push image to harbor

教育专家王中泽老师一招解决学生问题
随机推荐
[Oracle database] mammy tutorial day03 Sorting Query
12. integer to Roman numeral
[analysis of STL source code] summary notes (3): vector introduction
一、SQLServer2008安装(带密码)、创建数据库、C#窗体项目测试
软件测试周刊(第75期):唯有平视,才能看见真实的自己。
webserver
Analyse du contrat du modèle de taux composé
Leetcode-104. Maximum Depth of Binary Tree
教育专家王中泽老师一招解决学生问题
@Jsonproperty annotation
P3811 [template] multiplicative inverse
Server parameter adjustment record
自动化测试的生命周期是什么?
The rotation of the earth and the moon (II)
Outer margin collapse
[STL source code analysis] summary notes (5): a good helper for understanding iterators --list
213. house raiding II
Mybags puls will report an error invalid bound statement (not found) when writing an SQL statement in the XML file:
Mobile console Gobang (first draft of detailed design)
SQLZOO刷题记录-3