| 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() { |
| 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(); |
| 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() { |
| 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 { |
| 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 |