1 // Copyright 2018 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base.task; 6 7 import android.os.Handler; 8 9 import androidx.annotation.Nullable; 10 11 import org.jni_zero.JNINamespace; 12 13 /** 14 * Implementation of the abstract class {@link SingleThreadTaskRunner}. Before native initialization 15 * tasks are posted to the {@link java android.os.Handler}, after native initialization they're 16 * posted to a base::SingleThreadTaskRunner which runs on the same thread. 17 */ 18 @JNINamespace("base") 19 public class SingleThreadTaskRunnerImpl extends TaskRunnerImpl implements SingleThreadTaskRunner { 20 @Nullable private final Handler mHandler; 21 22 /** 23 * @param handler The backing Handler if any. Note this must run tasks on the 24 * same thread that the native code runs a task with |traits|. 25 * If handler is null then tasks won't run until native has 26 * initialized. 27 * @param traits The TaskTraits associated with this SingleThreadTaskRunnerImpl. 28 */ SingleThreadTaskRunnerImpl(Handler handler, @TaskTraits int traits)29 public SingleThreadTaskRunnerImpl(Handler handler, @TaskTraits int traits) { 30 super(traits, "SingleThreadTaskRunnerImpl", TaskRunnerType.SINGLE_THREAD); 31 mHandler = handler; 32 } 33 34 @Override belongsToCurrentThread()35 public boolean belongsToCurrentThread() { 36 Boolean belongs = belongsToCurrentThreadInternal(); 37 if (belongs != null) return belongs.booleanValue(); 38 assert mHandler != null; 39 return mHandler.getLooper().getThread() == Thread.currentThread(); 40 } 41 42 @Override schedulePreNativeTask()43 protected void schedulePreNativeTask() { 44 // if |mHandler| is null then pre-native task execution is not supported. 45 if (mHandler == null) { 46 return; 47 } else { 48 mHandler.post(mRunPreNativeTaskClosure); 49 } 50 } 51 52 @Override schedulePreNativeDelayedTask(Runnable task, long delay)53 protected boolean schedulePreNativeDelayedTask(Runnable task, long delay) { 54 if (mHandler == null) return false; 55 // In theory it would be fine to delay these tasks until native is initialized and post them 56 // to the native task runner, but in practice some tests don't initialize native and still 57 // expect delayed tasks to eventually run. There's no good reason not to support them here, 58 // there are so few of these tasks that they're very unlikely to cause performance problems. 59 mHandler.postDelayed(task, delay); 60 return true; 61 } 62 } 63