1/*
2 * Copyright (C) 2013 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.inputmethod.latin.utils;
18
19import android.util.Log;
20
21import java.util.concurrent.CountDownLatch;
22import java.util.concurrent.TimeUnit;
23
24/**
25 * This class is a holder of the result of an asynchronous computation.
26 *
27 * @param <E> the type of the result.
28 */
29public class AsyncResultHolder<E> {
30
31    private final Object mLock = new Object();
32
33    private E mResult;
34    private final String mTag;
35    private final CountDownLatch mLatch;
36
37    public AsyncResultHolder(final String tag) {
38        mTag = tag;
39        mLatch = new CountDownLatch(1);
40    }
41
42    /**
43     * Sets the result value of this holder.
44     *
45     * @param result the value to set.
46     */
47    public void set(final E result) {
48        synchronized(mLock) {
49            if (mLatch.getCount() > 0) {
50                mResult = result;
51                mLatch.countDown();
52            }
53        }
54    }
55
56    /**
57     * Gets the result value held in this holder.
58     * Causes the current thread to wait unless the value is set or the specified time is elapsed.
59     *
60     * @param defaultValue the default value.
61     * @param timeOut the maximum time to wait.
62     * @return if the result is set before the time limit then the result, otherwise defaultValue.
63     */
64    public E get(final E defaultValue, final long timeOut) {
65        try {
66            return mLatch.await(timeOut, TimeUnit.MILLISECONDS) ? mResult : defaultValue;
67        } catch (InterruptedException e) {
68            Log.w(mTag, "get() : Interrupted after " + timeOut + " ms");
69            return defaultValue;
70        }
71    }
72}
73