消息队列排队过程中的消息。这第一条消息将首先被处理。但假设消息本身指定要处理的时间。我们必须等待,直到时间的消息处理能力。新闻MessageQueue正在使用Message类的表示,队列中的邮件保存结构清单,Message内部对象包括:next变量,此变量指向下一个消息对象。

MessageQueue中的两个主要函数是“取出消息”和“加入消息”,各自是next()和enquenceMessage()。

next()函数

final Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0; for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(mPtr, nextPollTimeoutMillis); synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
final Message msg = mMessages;
if (msg != null) {
final long when = msg.when;
if (now >= when) {
mBlocked = false;
mMessages = msg.next;
msg.next = null;
if (Config.LOGV) Log.v("MessageQueue", "Returning message: " + msg);
return msg;
} else {
nextPollTimeoutMillis = (int) Math.min(when - now, Integer.MAX_VALUE);
}
} else {
nextPollTimeoutMillis = -1;
} // If first time, then get the number of idlers to run.
if (pendingIdleHandlerCount < 0) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount == 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
} if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
} // Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf("MessageQueue", "IdleHandler threw exception", t);
} if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
} // Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}

该函数的内部流程分三步:

1. 调用nativePollOnce(mPtr, int time)。这是一个JNI函数,作用是从消息队列中取出一个消息。

MessageQueue类内部本身并没有保存消息队列,真正的消息队列数据保存在JNI中的C代码中,在C环境中创建了一个NativeMessageQueue数据对象。这就是nativePollOnce()第一个參数的意义。它是一个int型变量,在C环境中。该变量被强制转换为一个NativeMessageQueue对象。在C环境中。假设消息队列中没有消息,将导致当前线程被挂起(wait),假设消息队列中有消息,则C代码中将把该消息赋值给Java环境中的mMessages变量。

2. 接下来的代码被包括在synchronized(this)中,this被用作取消息和写消息的锁。不过推断消息所指定的运行时间是否到了。

假设到了。就返回该消息。并将mMessages变量置空。假设时间还没有到,则尝试读取下一个消息。

3. 假设mMessages为空,则说明C环境中的消息队列没有可运行的消息了,因此,运行mPendingIdleHanlder列表中的“空暇回调函数”。

能够向MessageQueue中注冊一些“空暇回调函数”。从而当线程中没有消息可处理的时候去运行这些“空暇代码”。

enquenceMessage()函数

final boolean enqueueMessage(Message msg, long when) {
if (msg.when != 0) {
throw new AndroidRuntimeException(msg
+ " This message is already in use.");
}
if (msg.target == null && !mQuitAllowed) {
throw new RuntimeException("Main thread not allowed to quit");
}
final boolean needWake;
synchronized (this) {
if (mQuiting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
} else if (msg.target == null) {
mQuiting = true;
} msg.when = when;
//Log.d("MessageQueue", "Enqueing: " + msg);
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
needWake = mBlocked; // new head, might need to wake up
} else {
Message prev = null;
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
msg.next = prev.next;
prev.next = msg;
needWake = false; // still waiting on head, no need to wake up
}
}
if (needWake) {
nativeWake(mPtr);
}
return true;
}

该函数内部分为两步:

1. 将參数msg赋值给mMessages。

2. 调用nativeWake(mPtr)。这是一个JNI函数,其内部会将mMessages消息加入到C环境中的消息队列中,并假设该消息线程正在等待(wait)状态,然后唤醒线程。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

【核心研究】消息队列_MessageQueue的更多相关文章

  1. MQ选型对比ActiveMQ,RabbitMQ,RocketMQ,Kafka 消息队列框架选哪个?

    最近研究消息队列,发现好几个框架,搜罗一下进行对比,说一下选型说明: 1)中小型软件公司,建议选RabbitMQ.一方面,erlang语言天生具备高并发的特性,而且他的管理界面用起来十分方便.不考虑r ...

  2. MSMQ消息队列的安装、启用

    最近研究消息队列,先从微软自带的MSMQ开始,百度如何安装,方式如下: 控制面板---程序和功能--启用和关闭windows功能--Microsoft Message Queue(MSMQ)服务器 默 ...

  3. 高性能消息队列 CKafka 核心原理介绍(上)

    欢迎大家前往腾讯云技术社区,获取更多腾讯海量技术实践干货哦~ 作者:闫燕飞 1.背景 Ckafka是基础架构部开发的高性能.高可用消息中间件,其主要用于消息传输.网站活动追踪.运营监控.日志聚合.流式 ...

  4. 【iCore4 双核心板_uC/OS-II】例程九:消息队列

    一.实验说明: 前面介绍通过信息传递可以进行任务间的交流,信息也可以直接发送给一个任务,在uC/OS-II中每一个任务在它们内部都有一个消息队列,也即任务消息队列,用户可以直接给一个任务发送消息,不需 ...

  5. 高并发架构系列:MQ消息队列的12点核心原理总结

    消息队列已经逐渐成为分布式应用场景.内部通信.以及秒杀等高并发业务场景的核心手段,它具有低耦合.可靠投递.广播.流量控制.最终一致性 等一系列功能. 无论是 RabbitMQ.RocketMQ.Act ...

  6. RocketMQ读书笔记5——消息队列的核心机制

    [Broker简述] Broker是RocketMQ的核心,大部分“重量级”的工作都是由Broker完成的,包括: 1.接受Producer发过来的消息: 2.处理Consumer的消费信息请求: 3 ...

  7. 消息队列MQ核心原理全面总结(11大必会原理)

    消息队列已经逐渐成为分布式应用场景.内部通信.以及秒杀等高并发业务场景的核心手段,它具有低耦合.可靠投递.广播.流量控制.最终一致性 等一系列功能. 无论是 RabbitMQ.RocketMQ.Act ...

  8. MQ消息队列的12点核心原理总结

    1. 消息生产者.消息者.队列 消息生产者Producer:发送消息到消息队列. 消息消费者Consumer:从消息队列接收消息. Broker:概念来自与Apache ActiveMQ,指MQ的服务 ...

  9. NoSQL初探之人人都爱Redis:(3)使用Redis作为消息队列服务场景应用案例

    一.消息队列场景简介 “消息”是在两台计算机间传送的数据单位.消息可以非常简单,例如只包含文本字符串:也可以更复杂,可能包含嵌入对象.消息被发送到队列中,“消息队列”是在消息的传输过程中保存消息的容器 ...

随机推荐

  1. c# Use Properties Instead of Accessible Data Members

    advantage of properties: 1 properties can be used in data binding, public data member can not. 2 dat ...

  2. windbg更改cmd的token提升其特权

    采用windbg 调试xp. 执行cmd.whoami检查权限如下面: 以下要做的就是把cmd.exe 的token值用system的token替换. 1.  Ctrl + break ,windbg ...

  3. Android程序猿学习路径

    而一些工作,而不仅仅是通信毕业生,很多学生没有工作或熟练Android工作人员指导的情况下,,如何学习Android而提高Android更多关注的水平. 享: 1.Android知识 1.1.站点资源 ...

  4. POJ 2538 WERTYU水的问题

    [题目简述]:题意非常easy,没有trick. [分析]:事实上这题还是挺有趣的,在 算法竞赛入门经典中也有这一题. 详见代码: // 120K 0Ms /* 边学边做 -- */ // 字符串:W ...

  5. javascript实现倒计时-------Day28

    先来两张图片,看一看今天写什么: 看到图片右上角是什么了么看到图片以下是什么了么 相信这个大家都不会陌生吧.那些生活中等着秒杀,等着抢小米人们,焦躁等待的你曾一秒一秒的盯着它看么,我不知道答案,可我知 ...

  6. javascript有用小技巧—实现分栏显示

    记得给师哥师姐測试考试系统的时候,看到他们的考试页面能够实现隐藏左边的考生信息部分,当时认为好高大上.好人性化. 如今学了javascript,我也能实现这个功能了,以下来显摆一下. 1.页面设计: ...

  7. Android Application Thread CPU GC Operatiing and OOM Question 0603-随手笔记

    面前app当完成测试,没问题,以完成整个老龄化阶段包含数据收发器,关键在 adb shell top -m 5  我发现我的 app pid 占用  CPU是最多的,事实上我想说写一个app是不难,你 ...

  8. [Android]Can&#39;t create handler inside thread that has not called Looper.prepare()

    更新是由于在新的线程来打开UI只有一个错误.子线程更新主线程UI需要使用Handler. 还有比如今天出现以下错误.码,如以下: send.setOnClickListener(new OnClick ...

  9. MySQL各种日期类型与整型(转)

    日期类型 存储空间 日期格式 日期范围 datetime 8 bytes YYYY-MM-DD HH:MM:SS 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59 t ...

  10. Android - 用Fragments实现动态UI - 使用Android Support Library

    Android Support Library提供了一个带有API库的JAR文件来让你可以在使用最新的Android API的同时也也已在早期版本的Android上运行.例如,Support Libr ...