Home | History | Annotate | Download | only in future
      1 /*
      2  * Copyright (C) 2016 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
      5  * use this file except in compliance with the License. You may obtain a copy of
      6  * 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, WITHOUT
     12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     13  * License for the specific language governing permissions and limitations under
     14  * the License.
     15  */
     16 
     17 package com.googlecode.android_scripting.future;
     18 
     19 import java.util.concurrent.CountDownLatch;
     20 import java.util.concurrent.Future;
     21 import java.util.concurrent.TimeUnit;
     22 
     23 /**
     24  * FutureResult represents an eventual execution result for asynchronous operations.
     25  *
     26  * @author Damon Kohler (damonkohler (at) gmail.com)
     27  */
     28 public class FutureResult<T> implements Future<T> {
     29 
     30     private final CountDownLatch mLatch = new CountDownLatch(1);
     31     private volatile T mResult = null;
     32 
     33     public void set(T result) {
     34         mResult = result;
     35         mLatch.countDown();
     36     }
     37 
     38     @Override
     39     public boolean cancel(boolean mayInterruptIfRunning) {
     40         return false;
     41     }
     42 
     43     @Override
     44     public T get() throws InterruptedException {
     45         mLatch.await();
     46         return mResult;
     47     }
     48 
     49     @Override
     50     public T get(long timeout, TimeUnit unit) throws InterruptedException {
     51         mLatch.await(timeout, unit);
     52         return mResult;
     53     }
     54 
     55     @Override
     56     public boolean isCancelled() {
     57         return false;
     58     }
     59 
     60     @Override
     61     public boolean isDone() {
     62         return mResult != null;
     63     }
     64 
     65 }
     66