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 import java.util.concurrent.LinkedBlockingQueue; | |
| 9 | |
| 10 /** | |
| 11 * A package protected MessageLoop class for use in | |
| 12 * {@link CronetHttpURLConnection} | |
| 13 */ | |
| 14 final class MessageLoop { | |
| 15 private final BlockingQueue<Runnable> mQueue; | |
| 16 // A reusable runnable to quit the message loop. | |
| 17 private final Runnable mQuitTask; | |
| 18 // Indicates whether this message loop is currently running. | |
| 19 private boolean mLoopRunning; | |
| 20 | |
| 21 public MessageLoop() { | |
| 22 mQueue = new LinkedBlockingQueue<Runnable>(); | |
| 23 mQuitTask = new Runnable() { | |
| 24 @Override | |
| 25 public void run() { | |
| 26 mLoopRunning = false; | |
| 27 } | |
| 28 }; | |
| 29 } | |
| 30 | |
| 31 /** | |
| 32 * Runs the message loop. Be sure to call {@link MessageLoop#postQuitTask()} | |
| 33 * to end the loop. | |
| 34 */ | |
| 35 public void loop() { | |
| 36 if (mLoopRunning) { | |
| 37 throw new IllegalStateException( | |
| 38 "Cannot run loop when it is already running."); | |
| 39 } | |
| 40 mLoopRunning = true; | |
| 41 while (mLoopRunning) { | |
| 42 try { | |
| 43 Runnable task = mQueue.take(); // Blocks if the queue is empty. | |
| 44 task.run(); | |
| 45 } catch (InterruptedException e) { | |
| 46 throw new RuntimeException(e); | |
|
xunjieli
2014/11/26 16:11:56
I am not sure what I should do to handle Interrupt
mef
2014/11/26 16:36:04
It sounds like you can get that exception when you
mmenke
2014/11/26 17:09:12
Yes, it should quit the loop (Which re-throwing th
xunjieli
2014/11/26 18:37:14
Done.
| |
| 47 } | |
| 48 } | |
| 49 } | |
| 50 | |
| 51 /** | |
| 52 * Posts a reusable runnable, {@link #mQuitTask} to quit the loop. This | |
| 53 * causes the {@link #loop()} to terminate after processing all currently | |
| 54 * enqueued messages. | |
| 55 */ | |
| 56 public void postQuitTask() { | |
| 57 try { | |
| 58 mQueue.put(mQuitTask); | |
| 59 } catch (InterruptedException e) { | |
| 60 throw new RuntimeException(e); | |
| 61 } | |
| 62 } | |
| 63 | |
| 64 /** | |
| 65 * Posts a task to the message loop. | |
| 66 */ | |
| 67 public void postTask(Runnable task) { | |
| 68 if (task == null) { | |
| 69 throw new IllegalArgumentException(); | |
| 70 } | |
| 71 try { | |
| 72 mQueue.put(task); | |
| 73 } catch (InterruptedException e) { | |
| 74 throw new RuntimeException(e); | |
| 75 } | |
| 76 } | |
| 77 } | |
| OLD | NEW |