| Index: components/cronet/android/java/src/org/chromium/net/urlconnection/MessageLoop.java
|
| diff --git a/components/cronet/android/java/src/org/chromium/net/urlconnection/MessageLoop.java b/components/cronet/android/java/src/org/chromium/net/urlconnection/MessageLoop.java
|
| new file mode 100644
|
| index 0000000000000000000000000000000000000000..5a64db06e6ed6b4ab65ffad51c73ab697b7dfe43
|
| --- /dev/null
|
| +++ b/components/cronet/android/java/src/org/chromium/net/urlconnection/MessageLoop.java
|
| @@ -0,0 +1,68 @@
|
| +// Copyright 2014 The Chromium Authors. All rights reserved.
|
| +// Use of this source code is governed by a BSD-style license that can be
|
| +// found in the LICENSE file.
|
| +
|
| +package org.chromium.net.urlconnection;
|
| +
|
| +import java.util.concurrent.BlockingQueue;
|
| +import java.util.concurrent.LinkedBlockingQueue;
|
| +
|
| +/**
|
| + * A package protected MessageLoop class for use in
|
| + * {@link CronetHttpURLConnection}
|
| + */
|
| +final class MessageLoop {
|
| + private final BlockingQueue<Runnable> mQueue;
|
| + // A reusable runnable to quit the message loop.
|
| + private final Runnable mQuitTask;
|
| + // Indicates whether this message loop is currently running.
|
| + private boolean mLoopRunning;
|
| +
|
| + public MessageLoop() {
|
| + mQueue = new LinkedBlockingQueue<Runnable>();
|
| + mQuitTask = new Runnable() {
|
| + @Override
|
| + public void run() {
|
| + mLoopRunning = false;
|
| + }
|
| + };
|
| + }
|
| +
|
| + /**
|
| + * Runs the message loop. Be sure to call {@link MessageLoop#postQuitTask()}
|
| + * to end the loop.
|
| + * @throws InterruptedException
|
| + */
|
| + public void loop() throws InterruptedException {
|
| + if (mLoopRunning) {
|
| + throw new IllegalStateException(
|
| + "Cannot run loop when it is already running.");
|
| + }
|
| + mLoopRunning = true;
|
| + while (mLoopRunning) {
|
| + Runnable task = mQueue.take(); // Blocks if the queue is empty.
|
| + task.run();
|
| + }
|
| + }
|
| +
|
| + /**
|
| + * Posts a reusable runnable, {@link #mQuitTask} to quit the loop. This
|
| + * causes the {@link #loop()} to terminate after processing all currently
|
| + * enqueued messages.
|
| + * @throws InterruptedException
|
| + */
|
| + public void postQuitTask() throws InterruptedException {
|
| + mQueue.put(mQuitTask);
|
| + }
|
| +
|
| + /**
|
| + * Posts a task to the message loop.
|
| + * @throws InterruptedException
|
| + */
|
| + public void postTask(Runnable task) throws InterruptedException {
|
| + if (task == null) {
|
| + throw new IllegalArgumentException();
|
| + }
|
| + mQueue.put(task);
|
| + }
|
| +}
|
|
|