Handler的runWithScissors()方法详解

一 概述

在研究 WMS 启动的时候看到了如下代码:

public static WindowManagerService main(final Context context,
    final InputManagerService im, final boolean showBootMsgs,
    final boolean onlyCore, WindowManagerPolicy policy,
    ActivityTaskManagerService atm, TransactionFactory transactionFactory) {
    //Handler的runWithScissors方法
        DisplayThread.getHandler().runWithScissors(() ->
                sInstance = new WindowManagerService(context, im,
                showBootMsgs, onlyCore, policy, atm, transactionFactory), 0);
        return sInstance;
}

经过跟踪代码和查询相关资料得出以下基本信息:

runWithScissors() 是 Handler 的一个方法,但是被标记为 @hide,不允许普通开发者调用。

这个方法算是比较冷门,因为通过搜索发现,只有很少的地方用到过这个方法,它的设计目的是:

在一个线程中通过 Handler 向另外一个线程发送一个任务,并等另外一个线程处理此任务后,再继续执行。

如果需要用到以上这个场景,我们就可以借助 Handler 的 runWithScissors() 来实现。虽然该方法被标记为 @hide,但是在 Framework 中,也有不少场景使用到它。不过它也有一些隐患,正是因为这些隐患,让 Android 工程师将其标为 @hide,不允许普通开发者使用。

今天我们就通过代码分析的方式来聊聊 Handler 的这个方法 runWithScissors(),以及它可能出现的一些问题。

二 Handler.runWithScissors

2.1 runWithScissors

先撇开 runWithScissors() 方法,既然这里存在 2 个线程间的通信,那肯定需要考虑多线程同步。首先想到的就是 Synchronized 锁和它的等待/通知机制,而通过 Handler 跨线程通信时,想要发送一个任务,Runnable 肯定比 Message 更适合。

接下来,我们看看 runWithScissors() 的实现是不是如我们预想一样。

public final boolean runWithScissors(@NonNull Runnable r, long timeout) {
        if (r == null) {
            throw new IllegalArgumentException("runnable must not be null");
        }
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout must be non-negative");
        }

        if (Looper.myLooper() == mLooper) {
            r.run();
            return true;
        }

        BlockingRunnable br = new BlockingRunnable(r);
        return br.postAndWait(this, timeout);
}

可以看到,runWithScissors() 接受一个 Runnable,并且可以设置超时时间。
流程也非常简单:

  • 先对入参进行校验
  • 如果当前线程和 Handler 的处理线程一致,则直接运行这个 Runnable
  • 线程不一致,则把 Runnable 封装到一个 BlockingRunnable 中,并执行其 postAndWait() 方法

我们继续看 BlockingRunnable 的源码:

private static final class BlockingRunnable implements Runnable {
    private final Runnable mTask;
    private boolean mDone;

    public BlockingRunnable(Runnable task) {
        //把任务赋值给mTask
        mTask = task;
    }

    @Override
    public void run() {
        try {
        //执行这个任务
            mTask.run();
        } finally {
            synchronized (this) {
            //任务执行完毕,标记mDone为true,并唤醒等待线程
                mDone = true;
                notifyAll();
            }
        }
    }

    public boolean postAndWait(Handler handler, long timeout) {
    //把本身的BlockingRunnable发送到handler线程中执行
        if (!handler.post(this)) {
            return false;
        }

        synchronized (this) {
            if (timeout > 0) {
                final long expirationTime = 
                SystemClock.uptimeMillis() + timeout;
                while (!mDone) {
                    long delay = expirationTime - SystemClock.uptimeMillis();
                    if (delay <= 0) {//超时返回
                        return false; // timeout
                    }
                    try {//否则一直等待
                        wait(delay);
                    } catch (InterruptedException ex) {
                    }
                }
            } else {//如果没有设置超时,则一直等待
                while (!mDone) {
                    try {
                        wait();
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }
        return true;
    }
}

待执行的任务,会记入 BlockingRunnable 的 mTask,等待后续被调用执行。

postAndWait() 的逻辑也很简单,先通过 handler 尝试将 BlockingRunnable 发出去,之后进入 Synchronized 临界区,尝试 wait() 阻塞。

如果设置了 timeout,则使用 wait(timeout) 进入阻塞,若被超时唤醒,则直接返回 false,表示任务执行失败。

那么现在可以看到 postAndWait() 返回 false 有 2 个场景:

  • Handler post() 失败,表示 Looper 出问题了
  • 等待超时,任务还没有执行结束

除了超时唤醒外,我们还需要在任务执行完后,唤醒当前线程。

回看 BlockingRunnable 的 run() 方法,run() 被 Handler 调度并在其线程中执行。在其中调用 mTask.run(),mTask 即我们需要执行的 Runnable 任务。执行结束后,标记 mDone 并通过 notifyAll() 唤醒等待。

任务发起线程,被唤醒后,会判断 mDone,若为 true 则任务执行完成,直接返回 true 退出。

2.2 Framework 中的使用

runWithScissors() 被标记为 @hide,应用开发一般是用不上的,但是在 Framework 中,却有不少使用场景。

WindowManagerService.java

public static WindowManagerService main(final Context context, ......) {
        DisplayThread.getHandler().runWithScissors(() ->
                sInstance = new WindowManagerService(context, im, ......), 0);
        return sInstance;
    }

private void initPolicy() {
     // 运行在"android.ui"线程
        UiThread.getHandler().runWithScissors(new Runnable() {
            @Override
            public void run() {
                WindowManagerPolicyThread.set(Thread.currentThread(),
                    Looper.myLooper());
                mPolicy.init(mContext, WindowManagerService.this,
                    WindowManagerService.this);
            }
        }, 0);
}

还有在 WindowManagerGlobal.java,DisplayPowerControllder.java,BrightnessTracker.java,WifiServiceImpl.java 等中有使用。

三 runWithScissors() 存在的问题

看似 runWithScissors() 通过 Synchronized 的等待通知机制,配合 Handler 发送 Runnable 执行阻塞任务,看似没有问题,但依然被 Android 工程师设为 @hide。

我们继续看看它的问题。

3.1 如果超时了,没有取消的逻辑

通过 runWithScissors() 发送 Runnable 时,可以指定超时时间。当超时唤醒时,是直接 false 退出。

当超时退出时,这个 Runnable 依然还在目标线程的 MessageQueue 中,没有被移除掉,它最终还是会被 Handler 线程调度并执行。

此时的执行,显然并不符合我们的业务预期。

3.2 可能造成死锁

而更严重的是,使用 runWithScissors() 可能造成调用线程进入阻塞,而得不到唤醒,如果当前持有别的锁,还会造成死锁。

我们通过 Handler 发送的 MessageQueue 的消息,一般都会得到执行,而当线程 Looper 通过 quit() 退出时,会清理掉还未执行的任务,此时发送线程,则永远得不到唤醒。

那么在使用 runWithScissors() 时,就要求 Handler 所在的线程 Looper,不允许退出,或者使用 quitSafely() 方式退出。

quit() 和 quitSafely() 都表示退出,会去清理对应的 MessageQueue,区别在于,qiut() 会清理 MessageQueue 中所有的消息,而 quitSafely() 只会清理掉当前时间点之后(when > now)的消息,当前时间之前的消息,依然会得到执行。

那么只要使用 quitSafely() 退出,通过 runWithScissors() 发送的任务,依然会被执行。

也就是说,安全使用 runWithScissors() 要满足 2 个条件:

  • Handler 的 Looper 不允许退出,例如 Android 主线程 Looper 就不允许退出
  • Looper 退出时,使用安全退出 quitSafely() 方式退出

四 总结

今天我们介绍了 Handler 的方法 runWithScissors() 以及其原理,可以通过阻塞的方式,向目标线程发送任务,并等待任务执行结束。

虽然被它标记为 @hide,无法直接使用,但这都是纯软件实现,我们其实可以自己实现一个 BlockingRunnable 去使用。当然原本存在的问题,在使用时也需要注意。

我们知道就算这个方法不被标记为 @hide,使用的场景也非常的少,但是它依然可以帮助我们思考一些临界问题,线程的同步、死锁,以及 Handler 的退出方式对消息的影响。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC中的Handler方法是用来处理HTTP请求的方法。在Spring MVC中,通过注解将一个普通的Java方法标记为一个Handler方法,并将其映射到特定的URL路径和HTTP请求方法。 常用的Handler方法注解有: 1. @RequestMapping:用于将Handler方法映射到指定的URL路径和HTTP请求方法。可以设置URL路径、请求方法、请求头等条件。 2. @GetMapping、@PostMapping、@PutMapping、@DeleteMapping:分别用于将Handler方法映射到GET、POST、PUT、DELETE请求。 3. @PathVariable:用于获取URL路径中的变量值,并将其作为方法参数。 4. @RequestParam:用于获取请求参数的值,并将其作为方法参数。 5. @RequestBody:用于获取请求体中的数据,并将其转换为方法参数的类型。 6. @ResponseBody:用于将方法返回值直接作为响应体返回给客户端。 一个典型的Handler方法示例如下: ```java @Controller @RequestMapping("/users") public class UserController { @GetMapping("/{id}") @ResponseBody public User getUserById(@PathVariable("id") Long id) { // 根据id查询用户信息并返回 } @PostMapping @ResponseBody public User createUser(@RequestBody User user) { // 创建用户并返回 } @PutMapping("/{id}") @ResponseBody public User updateUser(@PathVariable("id") Long id, @RequestBody User user) { // 根据id更新用户信息并返回 } @DeleteMapping("/{id}") @ResponseBody public void deleteUser(@PathVariable("id") Long id) { // 根据id删除用户 } } ``` 以上示例中,`@RequestMapping`注解将`UserController`类映射到"/users"路径下。`@GetMapping`、`@PostMapping`、`@PutMapping`、`@DeleteMapping`注解分别将不同的Handler方法映射到不同的HTTP请求方法。`@PathVariable`注解用于获取URL路径中的变量值,`@RequestBody`注解用于获取请求体中的数据。`@ResponseBody`注解将方法返回值直接作为响应体返回给客户端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值