• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 java.util.concurrent.atomic.AtomicInteger;
8 
9 /**
10  * Implementation of the abstract class {@link SequencedTaskRunner}. Uses AsyncTasks until
11  * native APIs are available.
12  */
13 public class SequencedTaskRunnerImpl extends TaskRunnerImpl implements SequencedTaskRunner {
14     private AtomicInteger mPendingTasks = new AtomicInteger();
15 
16     private volatile boolean mReadyToCreateNativeTaskRunner;
17 
18     /**
19      * @param traits The TaskTraits associated with this SequencedTaskRunnerImpl.
20      */
SequencedTaskRunnerImpl(@askTraits int traits)21     SequencedTaskRunnerImpl(@TaskTraits int traits) {
22         super(traits, "SequencedTaskRunnerImpl", TaskRunnerType.SEQUENCED);
23     }
24 
25     @Override
schedulePreNativeTask()26     protected void schedulePreNativeTask() {
27         if (mPendingTasks.getAndIncrement() == 0) {
28             super.schedulePreNativeTask();
29         }
30     }
31 
32     @Override
runPreNativeTask()33     protected void runPreNativeTask() {
34         super.runPreNativeTask();
35         if (mPendingTasks.decrementAndGet() > 0) {
36             if (!mReadyToCreateNativeTaskRunner) {
37                 // Kick off execution in the pre-native pool.
38                 super.schedulePreNativeTask();
39             } else {
40                 // Initialize native runner so it can take over tasks in queue.
41                 super.initNativeTaskRunner();
42             }
43         }
44     }
45 
46     @Override
initNativeTaskRunner()47     void initNativeTaskRunner() {
48         mReadyToCreateNativeTaskRunner = true;
49         // There are two possibilities:
50         // 1. There is no task currently running - native runner is initialized immediately.
51         //    Incrementing mPendingTaskCounter prevents concurrent calls to post(Delayed)Task
52         //    from starting task in pre-native pool while native runner is being initialized.
53         // 2. There is a task currently running in pre-native pool. The native runner will be
54         //    initialized when the task is completed.
55         if (mPendingTasks.getAndIncrement() == 0) {
56             super.initNativeTaskRunner();
57         }
58     }
59 }
60