当前位置:网站首页>Summary of Android interview questions in 2020 (intermediate)
Summary of Android interview questions in 2020 (intermediate)
2022-06-24 04:24:00 【Granger_ g】
This blog post is reproduced from Jianshu :https://www.jianshu.com/p/c7b6c6851231
JVM The loading principle of
1. Compiling mechanism
As can be seen from the figure below java The file has been compiled once ,java Code compiled into java Bytecode (class file ). Then use different virtual machines on different platforms (JVM) explain , Interpreted as machine code , And then execute . thus it can be seen , If we want to mac Running on the system , Just install one mac Of java Virtual machine is OK . This is the same. java A compilation of , Run anywhere

JVM Loading mechanism
2. Class loading mechanism

Class loading mechanism
1. load
Loading is simply a three-step process .
First step : Get the binary byte stream, that is, the above class file .
The second step : Transform the static storage structure into the runtime data structure in the method area .
The third step : Generate an object to put into java In the pile , As a reference to the method area .
2. verification
Verification is mainly to check whether the following items are correct
class Representation of documents ( magic number ),class Version number of the document ,class Whether each part of the document is correct ( Field table 、 Method sheets, etc ), Validate constant pool ( constant type 、 Whether the constant type data structure is correct ,utf-8 Is it standard ), Metadata validation ( Parent class validation , Inheritance verification ,final verification ), Bytecode ( Instructions ) verification , Symbol reference validation ( Whether the corresponding field can be found according to the symbol 、 surface 、 Such method )
If one item is wrong , The verification will fail .
3. Get ready
The preparation phase allocates memory for class variables And set class variable initialization . In the process , Only right static Class variable for memory allocation , At this time, only memory is allocated , No replication , All class variables are initialization values . If it is final Words , Will be directly mapped to the constant pool . It will be assigned directly in the preparation stage .
4. analysis
The parsing phase is to read symbolic references for parsing . Resolve symbolic references to direct references ( A pointer or offset to a target ). The parsing mainly involves classes , Interface , Field , Such method .
5. initialization
Initialization is execution <clinte><linte> Method process , <clinte> For static variables , Static code block to initialize ,<linte> Initialize the class .
6. Use
The use phase uses this class.
7. uninstall
The uninstall phase is not in use , take class To uninstall .
3. Class loader

Class loader
As shown in the figure , Whenever our class is loaded , Will go to the class loader .
Our custom loader has a parent class , Namely AppClassLoader, and AppClassLoader There is also a parent class loader ExtClassLoader,ExtClassLoader There is also a parent class loader BootstarpClassLoader,BootstarpClassLoader Is the final loader .
When loading classes , Will start class loader , I will find it through the class loader defined by myself AppClassLoader, And then through AppClassLoader find ExtClassLoader, Re pass ExtClassLoader Find the final BootstarpClassLoader. You may see it here , Everyone has doubts , Why do I have my own loader , Why go to the loader of the parent class ? This mechanism is called the parental delegation mechanism , The purpose is to load tired security . That is to say, what my parent class loads will not be loaded by the child class , This guarantees that in the end BootstarpClassLoader To load the , You can guarantee that a class will be loaded only once . And when you judge two objects the same , The most important condition is whether a loader is used to load
The difference between global and local variables
1. Global variables are also called external variables , It is a variable defined outside the function . Which function does it not belong to , It belongs to a source program file . Its scope is the entire source program . Use global variables in functions , Generally, the global variables should be explained . Only global variables that have been specified in a function can be used . The specifier for the global variable is extern. But global variables defined before a function , Use within this function is not explained
2. Local variables are also called internal variables . Local variables are defined in functions . Its scope is limited to functions , It's illegal to use this variable after leaving the function
- In the same source file , Allow global and local variables to have the same name . In the scope of a local variable , Global variables don't work .
4. From the perspective of scope
Global variables have global scope . Global variables only need to be defined in one source file , It works on all source files . Of course , Other source files that do not contain global variable definitions need extern Keyword declares the global variable again .
Static local variables have local scope , It is initialized only once , It's been around since the first initialization until the end of the program , The difference between global variable and global variable is that global variable is visible to all functions , Static local variables are only visible to the function body that defines them .
Local variables have only local scope , It's an automatic object (auto), It doesn't always exist while the program is running , It only exists during function execution , After the execution of a call to the function , Variables are revoked , The memory it uses is also reclaimed .
Static global variables also have global scope , It differs from global variables in that if the program contains multiple files , It works in the document that defines it , It doesn't work on other documents , Namely be static Keyword decorated variables have file scope . So even if two different source files define static global variables with the same name , They are also different variables .
5. From the perspective of allocated memory space :
Global variables , Static local variables , Static global variables all allocate space in static storage , And local variables allocate space in the stack .
Global variables themselves are static storage , Static global variables are also static storage . There is no difference between the two in the way of storage . The difference between the two is that the scope of non static global variables is the whole source program , When a source program consists of multiple source files , Non static global variables are valid in all source files . Static global variables limit their scope , That is, it is only valid in the source file where the variable is defined , It cannot be used in other source files of the same source program . Because the scope of static global variables is limited to one source file , Can only be used for functions within the source file , So you can avoid causing errors in other source files .
1)、 Static variables are placed in the program's static data store ( The whole picture can be seen ) in , In this way, the original assignment can be kept at the next call . This is the difference between stack variable and heap variable .
2)、 Variable usage static Tell the compiler , I am only visible in the range of variables . This is the difference between it and global variables .
As can be seen from the above analysis , Changing a local variable to a static variable changes its storage mode, that is, its lifetime . Changing a global variable to a static variable changes its scope , It limits its use . therefore static The function of this specifier is different in different places . Attention should be paid to .
Tips:
A. If the global variable is only in a single C File access , You can change this variable to a static global variable , To reduce the coupling between modules ;
B. If global variables are accessed only by a single function , You can change this variable to the static local variable of this function , To reduce the coupling between modules ;
C. Design and use access dynamic global variables 、 Static global variables 、 When a function of a static local variable , The question of reentry needs to be considered , Because they're all in static data storage , The whole picture can be seen ;
D. If we need a reentrant function , that , We must avoid using static Variable ( Such a function is called : belt “ Internal memory ” Function of function )
E. You have to use static Variables : For example, when the return value of a function is of pointer type , It must be static The address of the local variable as the return value , if auto type , Then return to the wrong pointer .
The difference between static method locks and non static method locks
1. A lock is a class object , A lock is an instance object .
2. If a class object is lock, Then all synchronization methods of the class object (static synchronized func) All by lock.
3. If the instance object is lock, All synchronization methods of the instance object (synchronized func) All by lock.
4. About locks on methods of the same class , From the object that called the method , If the object calling the method is the same , Then the locks must be the same , Otherwise it would be different . such as new A().x() and new A().x(), Objects of different , Locks are different , If A Of simple interest , Can be mutually exclusive .
5. Static method lock , Can be locked with all other static methods Mutually exclusive
Thread local ThreadLocal The role of
When using ThreadLocal When maintaining variables ,ThreadLocal Provide a separate copy of the variable for each thread that uses the variable , So each thread can independently change its own copy , It does not affect the copies corresponding to other threads .
ThreadLocal And synchronized Comparison of synchronization mechanisms
In the synchronization mechanism , Through the lock mechanism of the object, only one thread can access the variable at the same time . In this case, the variable is shared by multiple threads , Using the synchronization mechanism requires the program to carefully analyze when to read and write variables , When you need to lock an object , When to release the object lock and so on , It is relatively difficult to design and program .
ThreadLocal It's a thread local variable , It is a solution to access variables concurrently between multiple threads . and synchronized The way of locking is different ,ThreadLocal Locks are not provided at all , Instead, use space for time , Provide a separate copy of the variable for each thread , To ensure thread safety .
There are several ways to write the singleton mode
1. Hungry Chinese style
public class SingletonInstance {
// Private constructor
private static SingletonInstance (){
}
// Declare member variables
private static SingletonInstance singletonInstance = new SingletonInstance();
// Provide an external interface to obtain the instance
public static SingletonInstance getSingletonInstance(){
return singletonInstance ;
}
}
2. Slacker type
public class SingletonInstance {
// Private constructor
private SingletonInstance (){
}
// Declare member variables
private static SingletonInstance singletonInstance ;
// Provide an external interface to obtain the instance
public static SingletonInstance getSingletonInstance(){
if(singletonInstance == null){
singletonInstance = new SingletonInstance();
}
return singletonInstance ;
}
}
3.double check lock(dcl)
public class SingletonInstance {
// Private constructor
private SingletonInstance (){
}
// Declare member variables
private static SingletonInstance singletonInstance ;
// Provide an external interface to obtain the instance
public static SingletonInstance getSingletonInstance(){
if(singletonInstance == null){
synchronized (SingletonInstance.class){
// Judge twice whether it is null
if(singletonInstance==null){
singletonInstance = new SingletonInstance();
}
}
}
return singletonInstance ;
}
}
4. Static inner class
public class SingletonInstance {
// Private constructor
private SingletonInstance (){
}
private static class Builder{
// Declare member variables
private static SingletonInstance singletonInstance = new SingletonInstance();
}
// Provide an external interface to obtain the instance
public static SingletonInstance getSingletonInstance(){
return Builder.singletonInstance ;
}
}
Deadlock
Link to the original text
Deadlock , A deadlock in which several processes compete for resources while running , When the process is in this stalemate , If there is no external force , They will not be able to move forward . So let's take an example to describe , If there is a thread at this time A, Lock it first a Get the lock again b The order of getting locks , And there's another thread at the same time B, Lock it first b Relock a The order to get the lock
1. The cause of deadlock
a. Compete for resources
There are two types of resources in the system :
Deprivable resources , It refers to a process after obtaining such resources , This resource can be taken away by other processes or systems ,CPU Both main memory and main memory belong to the deprivable resources ;
The other type of resource is an inalienable resource , When the system allocates such resources to a process , You can't take it back by force , It can only be released after the process is used up , Like a tape drive 、 Printers, etc .
One of the competing resources in deadlock refers to the competitive and undeniable resources ( for example : There is only one printer in the system , Available for process P1 Use , Assume P1 The printer has been occupied , if P2 Continuing to ask the printer to print will block )
Competing resources in deadlock generation. Another type of resource is competing temporary resources ( Temporary resources include hardware interrupts 、 The signal 、 news 、 Messages in the buffer, etc ), Usually, the order of message communication is improper , A deadlock occurs
b. The order of advancement between processes is illegal
if P1 Keep the resources R1,P2 Keep the resources R2, The system is in an unsafe state , Because these two processes move forward , A deadlock may occur
for example , When P1 Run to the P1:Request(R2) when , Will cause R2 Has been P2 Occupy and block ; When P2 Run to the P2:Request(R1) when , It will also be due to R1 Has been P1 Occupy and block , A process deadlock occurs
2. The necessary conditions for deadlock
1. mutual exclusion : Processes require exclusive control of allocated resources , That is, in a period of time, a resource is occupied by only one process .
2. Request and hold conditions : When a process is blocked by a request for resources , Keep the acquired resources .
3. Conditions of non deprivation : The resources obtained by the process are not used up , Can't deprive , It can only be released by itself after use .
4. Loop waiting condition : In the life and death lock , There must be a process -- Circular chain of resources .
3. The basic solution to deadlock
1. One time allocation of resources : Allocate all resources at once , So there will be no more requests :( Break request condition )
As long as one resource is not allocated , No other resources are allocated to this process :( Please keep the condition )
2. Deprivable resources : That is, when a process gets some resources , But there are no other resources , Then release the occupied resources ( The destruction of the inalienable conditions )
Orderly allocation of resources : The system assigns a number to each type of resource , Each process requests resources in ascending order , Release is the opposite ( Destroy the loop waiting condition )
author :Wocus
link :https://www.jianshu.com/p/c7b6c6851231
source : Simple books
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .
边栏推荐
- Multi task video recommendation scheme, baidu engineers' actual combat experience sharing
- What is FTP? What is the FTP address of the ECS?
- [Mid Autumn Festival greeting new year with good gifts] Tengyun pioneer feedback exchange group received new benefits!
- How to spell the iframe address of the video channel in easycvr?
- Have you learned all these routines to solve bugs?
- Gpt/gpt2/dialogpt detailed explanation comparison and application - text generation and dialogue
- How to select a telemedicine program system? These four points are the key!
- Openeuler kernel technology sharing issue 20 - execution entity creation and switching
- 近两周ACM之DP总结
- Can the video streams of devices connected to easygbs from the intranet and the public network go through their respective networks?
猜你喜欢

多任务视频推荐方案,百度工程师实战经验分享

Weibo International Edition changed its name to Weibo light sharing Edition

Clang code coverage detection (pile insertion technology)

How does the compiler put the first instruction executed by the chip at the start address of the chip?

The official overclocking tool of Intel XTU supports win11 22h2 and 13th generation core Raptor Lake processors

什么是数据中台

ServiceStack. Source code analysis of redis (connection and connection pool)
uni-app进阶之认证【day12】

一款支持内网脱机分享文档的接口测试软件

mysql - sql执行过程
随机推荐
Huawei cloud gaussdb (for redis) unveiling issue 19: gaussdb (for redis) comprehensive comparison with CODIS
Summary of the activation function sigmoid relu tanh Gelu in machine learning and deep learning
近两周ACM之DP总结
How to gracefully handle and return errors in go (1) -- error handling inside functions
Two most practical methods for cadence OrCAD capture to batch modify network names graphic tutorial and video demonstration
2020年Android面试题汇总(初级)
Download files and close the enhanced module security configuration to visit the website for the first time using IE browser
大一下学期期末总结(补充知识漏洞)
Abnova荧光原位杂交(FISH)探针解决方案
web渗透测试----5、暴力破解漏洞--(8)PostgreSQL密码破解
ribbon
Pycharm from installation to full armament
Changjiang Dayong, director of openeuler community: jointly promote the new open source model of Euler and jointly build a new open source system
To the world's first full frame 3D games!
Advanced authentication of uni app [Day12]
Troubleshoot the high memory consumption of Go program
What is a virtual host server? What are the advantages?
How to do the right thing in digital marketing of consumer goods enterprises?
事件
[2021 "shadow seeking" medical artificial intelligence algorithm competition] Ti-One product use tutorial