Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright 2014 The Chromium Authors. All rights reserved. | |
| 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.net.urlconnection; | |
| 6 | |
| 7 import java.io.IOException; | |
| 8 import java.util.concurrent.BlockingQueue; | |
| 9 import java.util.concurrent.LinkedBlockingQueue; | |
| 10 | |
| 11 /** | |
| 12 * A package protected MessageLoop class for use in | |
| 13 * {@link CronetHttpURLConnection}. | |
| 14 */ | |
| 15 final class MessageLoop { | |
| 16 private final BlockingQueue<Runnable> mQueue; | |
| 17 // A reusable runnable to quit the message loop. | |
| 18 private final Runnable mQuitTask; | |
| 19 // Indicates whether this message loop is currently running. | |
| 20 private boolean mLoopRunning; | |
| 21 | |
| 22 public MessageLoop() { | |
| 23 mQueue = new LinkedBlockingQueue<Runnable>(); | |
| 24 mQuitTask = new Runnable() { | |
| 25 @Override | |
| 26 public void run() { | |
| 27 mLoopRunning = false; | |
| 28 } | |
| 29 }; | |
| 30 } | |
| 31 | |
| 32 /** | |
| 33 * Runs the message loop. Be sure to call {@link MessageLoop#postQuitTask()} | |
| 34 * to end the loop. | |
| 35 * @throws IOException | |
| 36 */ | |
| 37 public void loop() throws IOException { | |
| 38 if (mLoopRunning) { | |
| 39 throw new IllegalStateException( | |
| 40 "Cannot run loop when it is already running."); | |
| 41 } | |
| 42 mLoopRunning = true; | |
| 43 while (mLoopRunning) { | |
| 44 try { | |
| 45 Runnable task = mQueue.take(); // Blocks if the queue is empty. | |
| 46 task.run(); | |
| 47 } catch (InterruptedException e) { | |
| 48 throw new IOException(e); | |
|
mmenke
2014/12/02 19:01:49
This doesn't support resumption after an Interrupt
xunjieli
2014/12/02 20:35:34
OkHttp's implementation retries until the request
mmenke
2014/12/02 20:51:07
We should throw an exception of some sort, then, o
| |
| 49 } | |
| 50 } | |
| 51 } | |
| 52 | |
| 53 /** | |
| 54 * Posts a reusable runnable, {@link #mQuitTask} to quit the loop. This | |
| 55 * causes the {@link #loop()} to terminate after processing all currently | |
| 56 * enqueued messages. | |
| 57 * @throws IOException | |
| 58 */ | |
| 59 public void postQuitTask() throws IOException { | |
| 60 try { | |
| 61 mQueue.put(mQuitTask); | |
| 62 } catch (InterruptedException e) { | |
| 63 throw new IOException(e); | |
| 64 } | |
| 65 } | |
| 66 | |
| 67 /** | |
| 68 * Posts a task to the message loop. | |
| 69 * @throws IOException | |
| 70 */ | |
| 71 public void postTask(Runnable task) throws IOException { | |
| 72 if (task == null) { | |
| 73 throw new IllegalArgumentException(); | |
| 74 } | |
| 75 try { | |
| 76 mQueue.put(task); | |
| 77 } catch (InterruptedException e) { | |
| 78 throw new IOException(e); | |
| 79 } | |
| 80 } | |
| 81 } | |
| OLD | NEW |