1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.volley.mock; 18 19import com.android.volley.NetworkResponse; 20import com.android.volley.Request; 21import com.android.volley.Response; 22 23import java.util.concurrent.PriorityBlockingQueue; 24import java.util.concurrent.Semaphore; 25import java.util.concurrent.TimeUnit; 26import java.util.concurrent.TimeoutException; 27 28// TODO: the name of this class sucks 29@SuppressWarnings({ "serial", "rawtypes" }) 30public class WaitableQueue extends PriorityBlockingQueue<Request> { 31 private final Request<?> mStopRequest = new MagicStopRequest(); 32 private final Semaphore mStopEvent = new Semaphore(0); 33 34 // TODO: this isn't really "until empty" it's "until next call to take() after empty" 35 public void waitUntilEmpty(long timeoutMillis) 36 throws TimeoutException, InterruptedException { 37 add(mStopRequest); 38 if (!mStopEvent.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) { 39 throw new TimeoutException(); 40 } 41 } 42 43 @Override 44 public Request<?> take() throws InterruptedException { 45 Request<?> item = super.take(); 46 if (item == mStopRequest) { 47 mStopEvent.release(); 48 return take(); 49 } 50 return item; 51 } 52 53 private static class MagicStopRequest extends Request<Object> { 54 public MagicStopRequest() { 55 super("", null); 56 } 57 58 @Override 59 public Priority getPriority() { 60 return Priority.LOW; 61 } 62 63 @Override 64 protected Response<Object> parseNetworkResponse(NetworkResponse response) { 65 return null; 66 } 67 68 @Override 69 protected void deliverResponse(Object response) { 70 } 71 } 72} 73