Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(80)

Side by Side Diff: sync/test/android/javatests/src/org/chromium/sync/test/util/SimpleFuture.java

Issue 2130453004: [Sync] Move //sync to //components/sync. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Rebase. Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(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 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698