| OLD | NEW |
| (Empty) |
| 1 // Copyright 2015 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.sync.test.util; | |
| 6 | |
| 7 import org.chromium.base.Callback; | |
| 8 | |
| 9 /** | |
| 10 * A simple tool to make waiting for the result of an asynchronous operation eas
y. | |
| 11 * | |
| 12 * This class is thread-safe; the result can be provided and retrieved on any th
read. | |
| 13 * | |
| 14 * Example usage: | |
| 15 * | |
| 16 * final SimpleFuture<Integer> future = new SimpleFuture<Integer>(); | |
| 17 * getValueAsynchronously(new Callback<Integer>() { | |
| 18 * public void onResult(Integer result) { | |
| 19 * // Do some other work... | |
| 20 * future.provide(result); | |
| 21 * } | |
| 22 * } | |
| 23 * int value = future.get(); | |
| 24 * | |
| 25 * Or, if your callback doesn't need to do anything but provide the value: | |
| 26 * | |
| 27 * SimpleFuture<Integer> result = new SimpleFuture<Integer>(); | |
| 28 * getValueAsynchronously(result.createCallback()); | |
| 29 * int value = result.get(); | |
| 30 * | |
| 31 * @param <V> The type of the value this future will return. | |
| 32 */ | |
| 33 public class SimpleFuture<V> { | |
| 34 private static final int GET_TIMEOUT_MS = 10000; | |
| 35 | |
| 36 private final Object mLock = new Object(); | |
| 37 private boolean mHasResult = false; | |
| 38 private V mResult; | |
| 39 | |
| 40 /** | |
| 41 * Provide the result value of this future for get() to return. | |
| 42 * | |
| 43 * Any calls after the first are ignored. | |
| 44 */ | |
| 45 public void provide(V result) { | |
| 46 synchronized (mLock) { | |
| 47 if (mHasResult) { | |
| 48 // You can only provide a result once. | |
| 49 return; | |
| 50 } | |
| 51 mHasResult = true; | |
| 52 mResult = result; | |
| 53 mLock.notifyAll(); | |
| 54 } | |
| 55 } | |
| 56 | |
| 57 /** | |
| 58 * Get the value of this future, or block until it's available. | |
| 59 */ | |
| 60 public V get() throws InterruptedException { | |
| 61 synchronized (mLock) { | |
| 62 while (!mHasResult) { | |
| 63 mLock.wait(GET_TIMEOUT_MS); | |
| 64 } | |
| 65 return mResult; | |
| 66 } | |
| 67 } | |
| 68 | |
| 69 /** | |
| 70 * Helper function to create a {@link Callback} that will provide its result
. | |
| 71 */ | |
| 72 public Callback<V> createCallback() { | |
| 73 return new Callback<V>() { | |
| 74 @Override | |
| 75 public void onResult(V result) { | |
| 76 provide(result); | |
| 77 } | |
| 78 }; | |
| 79 } | |
| 80 } | |
| OLD | NEW |