面试官:"Handler的runWithScissors()了解吗?为什么Google不让开发者用?"

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

 [[334762]]

一、序

大家好,这里是承香墨影!

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

这个方法算是比较冷门,如果面试中被问及,面试者不知道时,通常面试官会换个问法:"如何在子线程通过 Handler 向主线程发送一个任务,并等主线程处理此任务后,再继续执行?"。

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

今天我们就来聊聊 Handler 的这个冷门的方法 runWithScissors(),以及它可能出现的一些问题。

二、Handler.runWithScissors()

2.1 runWithScissors()

先撇开 runWithScissors() 方法,既然这里存在 2 个线程的通信,那肯定需要考虑多线程同步。

首先想到的就是 Synchronized 锁和它的等待/通知机制,而通过 Handler 跨线程通信时,想要发送一个「任务」,Runnable 肯定比 Message 更适合。

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

  1. public final boolean runWithScissors(final Runnable r, long timeout) { 
  2.   if (r == null) { 
  3.     throw new IllegalArgumentException("runnable must not be null"); 
  4.   } 
  5.   if (timeout < 0) { 
  6.     throw new IllegalArgumentException("timeout must be non-negative"); 
  7.   } 
  8.  
  9.   if (Looper.myLooper() == mLooper) { 
  10.     r.run(); 
  11.     return true
  12.   } 
  13.  
  14.   BlockingRunnable br = new BlockingRunnable(r); 
  15.   return br.postAndWait(this, timeout); 

可以看到,runWithScissors() 接受一个 Runnable,并且可以设置超时时间。

流程也非常简单:

  1. 先简单的对入参进行校验;
  2. 如果当前线程和 Handler 的处理线程一致,则直接运行 run() 方法;
  3. 线程不一致,则通过 BlockingRunnable 包装一下,并执行其 postAndWait() 方法;

那再继续看看 BlockingRunnable 的源码。

  1. private static final class BlockingRunnable implements Runnable { 
  2.   private final Runnable mTask; 
  3.   private boolean mDone; 
  4.  
  5.   public BlockingRunnable(Runnable task) { 
  6.     mTask = task; 
  7.   } 
  8.  
  9.   @Override 
  10.   public void run() { 
  11.     try { 
  12.       // 运行在 Handler 线程 
  13.       mTask.run(); 
  14.     } finally { 
  15.       synchronized (this) { 
  16.         mDone = true
  17.         notifyAll(); 
  18.       } 
  19.     } 
  20.   } 
  21.  
  22.   public boolean postAndWait(Handler handler, long timeout) { 
  23.     if (!handler.post(this)) { 
  24.       return false
  25.     } 
  26.  
  27.     synchronized (this) { 
  28.       if (timeout > 0) { 
  29.         final long expirationTime = SystemClock.uptimeMillis() + timeout; 
  30.         while (!mDone) { 
  31.           long delay = expirationTime - SystemClock.uptimeMillis(); 
  32.           if (delay <= 0) { 
  33.             return false; // timeout 
  34.           } 
  35.           try { 
  36.             wait(delay); 
  37.           } catch (InterruptedException ex) { 
  38.           } 
  39.         } 
  40.       } else { 
  41.         while (!mDone) { 
  42.           try { 
  43.             wait(); 
  44.           } catch (InterruptedException ex) { 
  45.           } 
  46.         } 
  47.       } 
  48.     } 
  49.     return true
  50.   } 

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

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

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

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

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

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

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

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

2.2 Framework 中的使用

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

例如比较熟悉的 WMS 启动流程中,分别在 main() 和 initPolicy() 中,通过 runWithScissors() 切换到 "android.display" 和 "android.ui" 线程去做一些初始工作。

  1. private void initPolicy() { 
  2.   UiThread.getHandler().runWithScissors(new Runnable() { 
  3.     public void run() { 
  4.       // 运行在"android.ui"线程 
  5.       WindowManagerPolicyThread.set(Thread.currentThread(), Looper.myLooper()); 
  6.       mPolicy.init(mContext, WindowManagerService.this, WindowManagerService.this); 
  7.     } 
  8.   }, 0); 

例如上面代码,就是从 "android.display" 线程,通过切换到 "android.ui" 线程去执行任务。

三、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() 方式退出;

四、总结时刻

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

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

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

 

 

责任编辑:武晓燕 来源: 51CTO专栏
相关推荐

2017-02-14 15:18:44

GoogleAndroid

2022-08-02 06:31:32

Java并发工具类

2022-07-26 08:40:42

Java并发工具类

2021-02-19 10:02:57

HTTPSJava安全

2022-07-11 10:47:46

容器JAVA

2022-07-06 13:48:24

RedisSentinel机制

2022-06-30 08:14:05

Java阻塞队列

2023-12-06 09:10:28

JWT微服务

2021-01-21 07:53:29

面试官Promis打印e

2020-10-24 15:50:54

Java值传递代码

2016-03-17 11:06:46

跳槽加薪面试

2012-09-17 17:42:48

Google Play盈利开发者

2010-08-17 09:01:39

jQueryAPI

2022-12-27 08:39:54

MySQL主键索引

2022-06-08 13:54:23

指令重排Java

2022-06-30 14:31:57

Java阻塞队列

2022-06-10 13:56:42

Java

2020-09-26 22:04:32

数据安全传输HTTPSHTTP 协议

2013-09-03 09:42:13

Android开发者

2021-12-20 10:30:33

forforEach前端
点赞
收藏

51CTO技术栈公众号