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.ArrayDeque; 8 import java.util.concurrent.Executor; 9 10 class SerialExecutor implements Executor { 11 final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); 12 Runnable mActive; 13 14 @Override execute(final Runnable r)15 public synchronized void execute(final Runnable r) { 16 mTasks.offer( 17 () -> { 18 try { 19 r.run(); 20 } finally { 21 scheduleNext(); 22 } 23 }); 24 if (mActive == null) { 25 scheduleNext(); 26 } 27 } 28 scheduleNext()29 protected synchronized void scheduleNext() { 30 if ((mActive = mTasks.poll()) != null) { 31 AsyncTask.THREAD_POOL_EXECUTOR.execute(mActive); 32 } 33 } 34 } 35