編輯:關於 Android 開發
原文地址:https://blog.csdn.net/xplee0576/article/details/46875555
在 Android 中,我們在線程之間通信時通常采用消息機制,而這一機制所傳遞的正是 Message 對象。日常開發中,我們習慣使用 Message.obtain() 與 Handler.obtainMessage() 從 Message Pool 中獲取 Message,以避免直接構造 Message 對象。
那麼,Android 是否會因為 Message Pool 緩存的 Message 對象而導致 OOM 呢?對此可以明確回答:App 不會因 Message Pool 而 OOM。至於原因,不妨一步步往下看,心急的朋友也可以直接跳到最後一節——Message Pool 如何存放 Message。
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
從這段程式碼可以看到,Message 是由 sPool 直接賦值取得的,只有當池已空時才會 new 一個新對象。
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
public final Message obtainMessage() {
return Message.obtain(this);
}
可見 Handler.obtainMessage() 最終仍是調用 Message.obtain() 來獲取的。
// sometimes we store linked lists of these things
/*package*/ Message next;
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
private static boolean gCheckRecycle = true;
從程式碼可以清楚地看到,Message Pool 的數據結構實際上就是一個鏈表。sPool 是全局的消息池頭節點,sPoolSize 記錄鏈表長度,而 MAX_POOL_SIZE 則規定鏈表的最大長度為 50。
/** @hide */
public static void updateCheckRecycle(int targetSdkVersion) {
if (targetSdkVersion < Build.VERSION_CODES.LOLLIPOP) {
gCheckRecycle = false;
}
}
/**
* Return a Message instance to the global pool.
* You MUST NOT touch the Message after calling this function.
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
從程式碼分析來看,消息池存放的核心方法正是 recycleUnchecked(),其關鍵邏輯可分為兩步:
1、清空字段:將待回收的 Message 對象字段逐一置空(obj、data、callback 等),以避免因 Message 體積過大而使靜態的消息池造成記憶體洩漏。因此,無論原先的 Message 對象有多大,在被緩存進 Message Pool 之前都會被置空,這些緩存對象所佔的記憶體對整個 App 而言幾乎可以忽略。這也正是 Message Pool 不會導致 OOM 的根本原因。
2、線程安全地入池:以內置鎖(synchronized)的方式判斷當前池大小是否小於 50。若小於 50,則將該 Message 頭插到消息池鏈表;若已達到或超過 50,則直接丟棄,這些被丟棄的 Message 將交由 GC 回收處理。
由此可見,Message Pool 通過「有限緩存 + 對象複用 + 字段清空」的設計,在提升性能的同時有效規避了記憶體洩漏風險。
Android GUI 系統之 WMS(二)——窗口添加流程全解析
Android GUI 系統之 WMS(二)——窗口添加流程全解析 Android 上的窗口大致可以分成兩類:一類由系統進程管理,即系統窗口,例如狀態欄、導航欄;另一類由
註冊頁面實作(三):用 SharedPreferences 暫存帳號資料
要做什麼 註冊成功後把帳號記下來,下次打開登入頁自動帶入,是很基本也很常見的需求。SharedPreferences 就是為這種「少量、簡單的鍵值資料」而生的元件——它會
Android 自訂個性化進度條:用 layer-list 與 clip 打造圖片進度條
系統預設的 ProgressBar 樣式單調,想做出帶有自訂圖片的進度條該怎麼做?本文從原始碼出發,一步步示範如何實作水平與垂直的圖片式進度條。 一、效果預覽 目標是讓
Volley 框架實作:GET、POST、JSON 與圖片加載
Volley 框架實作:GET、POST、JSON 與圖片加載 Volley 是 Android 上常用的網路請求框架,適合高頻、小型網路請求。本文整理 GET、POST