当前位置:网站首页>Almost taken away by this wave of handler interview cannons~
Almost taken away by this wave of handler interview cannons~
2022-06-25 08:15:00 【Cattle within yards】
Handler yes Android The most frequently used message mechanism in , During the interview process in large factories these years , More and more . Although there are many friends who can complete the solution, there are few , What's going on ?
In fact, the reason is self-evident , Dachang right Handler All the interview questions have a certain depth . And I like the details ;
For example, I mentioned in my previous article ,Handler Of runWithScissors() Can achieve A Thread to B The thread sends a message , send A Thread is blocking , wait for B After the thread processes the message, it continues to execute . So the extended 2 The problem is ;
runWithScissors() What is the principle of ?
It's marked as @hide Is there any problem in not allowing it to be used ?
Another example , We know MessageQueue, In fact, it is based on the trigger time when Priority message queue . So in what scenario ,MessageQueue The news at the back of the middle , Will precede the news ahead , Scheduled to execute ?
These problems , If you don't look at the source code , Just stay at the use level , It's basically hard to figure out .
1:Handler In mechanism , What roles exist ? What functions do they undertake ?
- Handler: Message auxiliary class & External interface & towards MQ Deliver a message & The target handler of the message ;
- Message: The carrier of the message & By Handler The delivery & Bring their own Handler Handle & Built in message pool ;
- Looper: Circulator & hold MQ & Cycle from MQ Get message from & TLS Thread unique ;
- MessageQueue: Time based priority queue & Chain table structure & Java And C++ The ties of the layers ;
2:Handler Distribution event priority , Whether it can be intercepted ? What is the priority of interception ?
Handler in , adopt dispatchMessage() Process the message , There is a priority policy ;
- priority 1:msg,callback,run() - Monopoly ;
- priority 2:mCallback.handleMessage(msg) - The return value determines whether to intercept the message ;
- priority 3:handle.handleMessage();
3: The main thread Looper When to run ?
App Startup time , Will be called to ActivityThread in ,Looper It's in it main() Method ;main() Will actively call Looper.prepareMainLooper() and Looper.loop();Tips:ActivityThread Do not inherit from Thread, It's just an object running on the main thread ;
4:Handler Of Message It can be divided into 3 class ? What are the marks ?
- Sync Message: Ordinary Message;
- asynchronous Message:msg.setAsynchronous(true)
- Synchronization barrier :msg.target == null
5: The same Message Whether the object can be repeated send?
The key is how to define the same Message.
- Angle one :Java Object level , Reusable ;
reason :Message Maintained by the message pool , That is, the same object will be reused after being recycled ;| new Message & Message.obtain() - Angle two : Business level , It can't be reused ;
reason :Message adopt enqueueMessage() When you join the team , Will pass markInUse() Mark , Joining the team again can't pass isInUse() Check , Throw an exception ;
I sum up here BAT Dachang about Handler More than 100+ High frequency interview questions , Now it has been sorted into HD PDF Learning documents , If you need anything, you can Reply to me by private letter 666 Ready to pick up !!! It basically covers all angles , You can take a self-test . You can also brush it before the interview , After all Handler Although interview questions appear frequently , But don't panic when you meet .
6: scene :MessageQueue Is based on the trigger time when Priority queue of , Under what circumstances , Messages later in the queue will be executed first ? What is the principle ?
- scene : The first message is the synchronization message , The next message is asynchronous , And the queue head of the message queue is the synchronization barrier ;
- principle : The synchronization barrier will block MQ Synchronization messages in , Prioritize asynchronous messages ;
7:Message What's the use of synchronization barriers ? What's the point ? How to send a synchronization barrier ?
- purpose : Blocking MQ Synchronization Message Distribution of , Prioritize asynchronous messages , When there is no asynchronous message, it enters sleep , Until the synchronization barrier is removed ;
- significance : Allow asynchronous messages to take precedence over synchronous messages ;
- Synchronization barrier : special Message,target == null, Unable to get Handler Join the team and leave the team , Direct operation is required MQ; The team :postSyncBarrier(): Return to a barrier token; Out of the team :removeSyncBarrier()
8: What is asynchronous message ? How to send ?
- significance : It needs to be used with synchronous barrier , No, it's no different from synchronous messages ;
- Asynchronous messaging :setAsynchronous(true) → towards flags add to FLAG_ASYNCHRONOUS Mark
Send by Through asynchrony Handler send out → structure Handler when ,async Pass on true Before sending a message , Active call setAsynchronous(true)
Be on the safe side ,Android 9.0 Ordinary developers cannot use asynchronous messages , All sending methods are marked as @hide
9:Handler Of IdleHandler Mechanism , How to understand ? What's the use ?
Interface , Need to implement queueIdle() Method & It's defined in MQ in & With MQ mIdleHandlers Maintain storage
- purpose : Can be found in MQ When I'm about to be free , Processing tasks ;
- Logical point :MQ.next() in , When there are currently no pending messages , perform mIdleHandlers;
basis queueIdle() The return value is divided into : Continuous callback (true) & One time callback (false),false Will result in after execution , from mIdleHandlers Remove
10:IdleHandler Will the execution time affect the normal message distribution ?Handler How to deal with it internally ?
Meeting ;IdleHandler The time is uncontrollable ; After execution, it will reset nextPollTimeoutMillis = 0, Redistribute recent messages
11: Remove the message removeMessage() Why do you need two cycles ?
Optimize efficiency ;
- while-1: Remove message & Find the next pending message , Deposit in mMessages in ;
- while-2: from mMessages Start , Remove the subsequent qualified messages ;
12:Handler Of runWithScissors() Can be realized A Thread blocking waiting B The function that the thread continues to execute after processing the message , Why is it marked hide? What are the problems ? What's the reason ?
- Realization : take Runnable The packing is BlockingRunnable, It passes through synchronized + wait Has reached the awaited , stay r After the execution , call notifyAll() Wake up the child thread waiting for the queue , The child thread continues to execute ;
- problem : In the child thread Looper Use in , May lead to A Thread entry wait wait for , And never get notify Wake up the ;
- reason : Sub thread Looper Allow to exit , If packed BlockingRunnable Before being executed ,MessageQueue sign out , Then runnable It will never be carried out , Will lead to A Thread has been in wait wait for , Never be notify Wake up the ;
13:Looper.loop in , If there are no pending messages , Why not block UI?
The main thread is in MessageQueue When there is no message , Will be blocked. loop Of queue.next() Methods nativePollOnce() In the method .
The main thread is released CPU Resource goes to sleep , Until the next message arrives or a transaction occurs , Through to pipe How to write data at the writing end of the pipeline , To wake up the main thread . What we use here is epoll Mechanism .
epoll Mechanism is a kind of IO Multiplexing mechanism , Multiple descriptors can be monitored at the same time , When something happens , Immediately notify the corresponding program to read or write , Like a kind of callback The callback mechanism of . The main thread is dormant most of the time , It doesn't consume a lot of CPU resources . When a new message or transaction arrives , Will immediately wake up the main thread for processing , So it is imperceptible to users .
14: If Java layer MQ There is little news in , But the response time is very long , What is the reason ?
MQ In line , The Message Before Message Processing is time-consuming ;Native Too many layer messages ,Java layer MQ Message priority is the lowest , Finally deal with ;
15:Looper Of Printer Output log , What other uses ? What principle does it depend on ? What's the downside ?
- purpose : Performance monitoring ;
- principle : By filtering log memory , distinguish Message The point in time at which the execution of starts and ends , It can be judged and handled Message Time consuming , That is, the main route is stuck for a long time ;
- shortcoming :Printer There are a lot of string concatenation , When the message volume is large , Will cause performance damage ;| Measured data : There is Printer when , When the list slides quickly , The average frame rate is reduced 5 frame ;
16:Handler Sure IPC Correspondence ?
You can't ;Handler Can only be used for shared memory addresses 2 Threads communicating , That is, the same process 2 Threads communicating ;
17:Handler Why do I need to use the underlying epoll To sleep ?
Need to take into account Native Layer messages , Messages may come from the underlying hardware ; If only consider Java layer ,notify/wait That is to say ;
I sum up here BAT Dachang about Handler More than 100+ High frequency interview questions , Now it has been sorted into HD PDF Learning documents , If you need anything, you can Reply to me by private letter 666 Ready to pick up !!! It basically covers all angles , You can take a self-test . You can also brush it before the interview , After all Handler Although interview questions appear frequently , But don't panic when you meet .
边栏推荐
- allgero报错:Program has encountered a problem and must exit. The design will be saved as a .SAV file
- In 2022, which industry will graduates prefer when looking for jobs?
- Pychart's wonderful setting: copy immediately after canceling the comment and bring #
- What is the difference between agreement and service?
- Force buckle 272 Closest binary search tree value II recursion
- 力扣 272. 最接近的二叉搜索树值 II 递归
- 测一测现在的温度
- Opencv minimum filtering (not limited to images)
- 想转行学软件测试担心哪些问题?
- Looking for b-end product manager after years? I almost ruined myself
猜你喜欢
DNS protocol and its complete DNS query process
飞机引气系统的建模与故障仿真
Apache CouchDB Code Execution Vulnerability (cve-2022-24706) batch POC
电子学:第013课——实验 14:可穿戴的脉冲发光体
电子学:第010课——实验 9:时间与电容器
Overview of image super score: the past and present life of image super score in a single screen (with core code)
剑指offer刷题(简单等级)
Stm32cubemx Learning (5) Input capture Experiment
417 sequence traversal of binary tree 1 (102. sequence traversal of binary tree, 107. level traversal of binary tree II, 199. right view of binary tree, 637. layer average of binary tree)
Apache CouchDB 代码执行漏洞(CVE-2022-24706 )批量POC
随机推荐
What is the difference between agreement and service?
C # set up FTP server and realize file uploading and downloading
剑指offer刷题(中等等级)
C disk drives, folders and file operations
Niuke: flight route (layered map + shortest path)
Introduction to the main functions of the can & canfd comprehensive test and analysis software lkmaster of the new usbcan card can analyzer
June training (day 25) - tree array
417 sequence traversal of binary tree 1 (102. sequence traversal of binary tree, 107. level traversal of binary tree II, 199. right view of binary tree, 637. layer average of binary tree)
Use pytorch to build mobilenetv2 and learn and train based on migration
bat启动.NET Core
数论模板啊
黑点==白点(MST)
Electronics: Lesson 013 - Experiment 14: Wearable pulsed luminaries
洛谷P3313 [SDOI2014]旅行(树链+边权转点权)
RMQ interval maximum subscript query, interval maximum
[supplementary question] 2021 Niuke summer multi school training camp 6-n
Startup, shutdown and restart of Oracle and MySQL on Linux
PH neutralization process modeling
FFT [template]
socket问题记录