Handler must ask eight questions in the interview, if you meet you, you will earn

foreword

img

Handler has always been a frequent visitor in the interview process. Let's take a look at what can be played around Handler today.

The Handler mechanism is almost a must-ask question during an Android interview . Although I have seen the source code of the handler many times, some questions asked by the interviewer may not be able to answer them. Taking this opportunity, I will summarize the Handler knowledge points covered in the interview below.

topic level

1. Briefly describe the implementation principle of Handler

2. How many Handlers does a thread have? How many Loopers does a thread have? How to guarantee?

3. How does the Handler thread switch?

4. What is the reason for the Handler memory leak? How to solve?

5. Why doesn't the main thread initialize Looper?

6. How does Handler guarantee the security of MessageQueue concurrent access?

7. What is the blocking wake-up mechanism of Handler?

8. Can a Message be processed urgently? / What is a Handler synchronization barrier?

Detailed explanation of the problem

  1. Briefly describe the implementation principle of Handler

Handler is a mechanism used in the Android system to implement inter-thread communication and task scheduling. It is implemented based on the three core components of Android's Looper, MessageQueue and Message. The main working principle is as follows:

  • Create a Handler instance, which will be associated with a thread.
  • In the constructor of the Handler, it is necessary to obtain the Looper object of the thread, and then associate the Handler with the Looper to realize the binding between the Handler and the Looper.
  • In Handler's post(), sendMessage() and other methods, a Message object will be inserted into Looper's MessageQueue, and it will be taken out and processed while waiting for Looper to cycle.
  • Looper will continuously take Message from MessageQueue and pass it to Handler's dispatchMessage() method. The dispatchMessage() method is responsible for processing the fetched Message, and performs corresponding operations according to the type of the Message, such as callback and UI update.
  • Through inter-thread communication, tasks can be executed in different threads, thereby realizing multi-threaded programming.
  1. How many Handlers does a thread have? How many Loopers does a thread have? How to guarantee?

A thread can have multiple Handlers, because Handlers are implemented based on ThreadLocal, and each Handler instance is associated with a thread, but there can only be one Looper in the same thread.

The way to ensure that a thread has a Looper is:

  • After Looper.prepare(), call Looper.loop() to start the Looper loop.
  • Make sure that the Looper.loop() method is executed in the main thread, or manually call the Looper.prepare() and Looper.loop() methods in the main thread.
  1. How does the Handler thread switch?

The method for Handler to switch threads is: create a Handler instance in a new thread, and bind it to the Looper of the new thread. When a task needs to be executed in a new thread, the post() or sendMessage() method of Handler can be used to submit the task to the Looper of the new thread for processing.

  1. What is the reason for Handler memory leak? How to solve?

The reason for the Handler memory leak is that when the Activity or Fragment is destroyed, there may still be unprocessed Messages or Runnables in the Handler. These objects will hold references to the Handler, causing the Handler to fail to be recycled, thereby causing a memory leak.

Solution:

  • Use weak reference or WeakReference instead of strong reference to refer to Handler.
  • In the onDestroy() method of Activity or Fragment, call the removeCallbacksAndMessages() method of Handler to remove all Messages and Runnables.
  • For Message, you can use the removeCallbacksAndMessages() method of MessageQueue to remove.
  1. Why doesn't the main thread initialize Looper?

The main thread (UI thread) has initialized the Looper by default, so there is no need to manually call the Looper.prepare() and Looper.loop() methods.

This is because when the Android system starts the application, it will automatically create a Looper object for the main thread and start the Looper cycle. The ActivityThread class of the main thread contains a Looper object, and the Looper cycle will be started in the attach() method of the Application class.

  1. How does Handler ensure the security of MessageQueue concurrent access?

The Android system uses a synchronization barrier mechanism called a barrier (Barrier) to ensure the security of concurrent access to MessageQueue. In the enqueueMessage() method of MessageQueue, it will judge whether there is a synchronization barrier in the current queue, and if it exists, all messages after the synchronization barrier will be skipped to ensure that these messages will not be accessed concurrently.

  1. What is the blocking wake-up mechanism of Handler?

The blocking wake-up mechanism of the Handler means that in the MessageQueue of the Looper, when the number of Messages is too large, the Looper will enter the blocking state until a new Message arrives. When a new Message arrives, Looper will wake up and process the new Message.

The specific implementation is as follows:

  • Looper maintains a blocking queue in MessageQueue. When the number of messages in the blocking queue reaches a certain threshold, Looper will enter the blocking state.
  • When a new Message arrives, the Looper will remove a Message from the blocking queue and insert it into the MessageQueue, thereby waking up the Looper.
  • After the Looper wakes up, it will take out the new Message from the MessageQueue and process it.
  1. Can a Message be processed urgently?

You can use the setAsynchronous() method of Message to set a Message as an asynchronous message, and such a Message will be prioritized in the MessageQueue.

The specific implementation is as follows:

  • In the constructor of Message, you can use the Message.setAsynchronous() method to set the asynchronous flag bit of Message.
  • When a Message is set as an asynchronous message, in the MessageQueue, the asynchronous message will be processed first. After the asynchronous message is processed, the normal message will be processed.

at last

How to learn Handler better?

As long as you are a programmer, whether it is Java or Android, if you don’t read the source code and only look at the API documentation, it is just superficial, which is not good for the establishment and completion of our knowledge system and the improvement of actual combat technology.

What can really exercise your ability the most is to read the source code directly, not limited to reading the source code of the Android system, but also includes various excellent open source libraries.

Finally, in order to help you deeply understand the principles of Handler-related knowledge points and interview-related knowledge, here is a compilation of source codes related to Android development:

" Android development related source code analysis "

Due to the large content of the article and the limited space, the information has been organized into PDF documents. If you need the complete document of " Android Development Related Source Code Compilation and Analysis " , you can add WeChat to get it for free!

Table of contents

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-mKhaB2cH-1687853866244)(https://docimg3.docs.qq.com/image/9El_q1GRv_gn-rQDD6vL0w.png ?w=584&h=511)]

Guess you like

Origin blog.csdn.net/Gaga246/article/details/131456348