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.util.concurrent.BlockingQueue; | |
| 8 | |
| 9 /** | |
| 10 * A package protected MessageLoop class for use in | |
| 11 * {@link CronetHttpURLConnection} | |
| 12 */ | |
| 13 final class MessageLoop { | |
| 14 private final BlockingQueue<Message> mQueue; | |
| 15 | |
| 16 public MessageLoop(BlockingQueue<Message> queue) { | |
| 17 mQueue = queue; | |
| 18 } | |
| 19 | |
| 20 /** | |
| 21 * Runs the message loop. Be sure to call {@link MessageLoop#quit()} to end | |
| 22 * the loop. | |
| 23 */ | |
| 24 public void loop() { | |
|
mmenke
2014/11/26 14:59:46
Maybe throw an exception if already running on ano
xunjieli
2014/11/26 16:11:55
Done.
| |
| 25 while (true) { | |
| 26 try { | |
| 27 Message msg = mQueue.take(); // Blocks if the queue is empty. | |
| 28 if (msg.mTask != null) { | |
| 29 msg.mTask.run(); | |
| 30 } else { | |
| 31 // Quits the message loop. | |
| 32 break; | |
| 33 } | |
| 34 } catch (InterruptedException e) { | |
| 35 e.printStackTrace(); | |
|
mmenke
2014/11/26 14:59:46
Should we really just be silently eating these?
| |
| 36 } | |
| 37 } | |
| 38 } | |
| 39 | |
| 40 /** | |
| 41 * Quits the loop. This causes the {@link MessageLoop#loop()} to terminate | |
| 42 * after processing all currently enqueued messages. | |
| 43 */ | |
| 44 public void quit() { | |
|
mmenke
2014/11/26 14:59:46
postQuitMessage? That makes it clearer it doesn't
xunjieli
2014/11/26 16:11:56
Done.
| |
| 45 try { | |
| 46 mQueue.put(new Message(null)); | |
| 47 } catch (InterruptedException e) { | |
| 48 e.printStackTrace(); | |
| 49 } | |
| 50 } | |
| 51 | |
| 52 /** | |
| 53 * Message class that represents a task to run. | |
| 54 */ | |
| 55 static class Message { | |
|
mmenke
2014/11/26 14:59:46
Alternatively... Charles was concerned about maki
mmenke
2014/11/26 14:59:46
per other comment, suggest making this private.
xunjieli
2014/11/26 16:11:56
Done. That's neat! thanks!
| |
| 56 private final Runnable mTask; | |
| 57 | |
| 58 /** | |
| 59 * Constructs a Message with a given task. | |
| 60 * @param task If null, it is a quit signal to the message loop. | |
| 61 */ | |
| 62 public Message(Runnable task) { | |
| 63 mTask = task; | |
| 64 } | |
| 65 } | |
| 66 } | |
| OLD | NEW |