View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.http.concurrent;
28  
29  import org.apache.http.util.Args;
30  
31  import java.util.concurrent.CancellationException;
32  import java.util.concurrent.ExecutionException;
33  import java.util.concurrent.Future;
34  import java.util.concurrent.TimeUnit;
35  import java.util.concurrent.TimeoutException;
36  
37  /**
38   * Basic implementation of the {@link Future} interface. {@code BasicFuture}
39   * can be put into a completed state by invoking any of the following methods:
40   * {@link #cancel()}, {@link #failed(Exception)}, or {@link #completed(Object)}.
41   *
42   * @param <T> the future result type of an asynchronous operation.
43   * @since 4.2
44   */
45  public class BasicFuture<T> implements Future<T>, Cancellable {
46  
47      private final FutureCallback<T> callback;
48  
49      private volatile boolean completed;
50      private volatile boolean cancelled;
51      private volatile T result;
52      private volatile Exception ex;
53  
54      public BasicFuture(final FutureCallback<T> callback) {
55          super();
56          this.callback = callback;
57      }
58  
59      @Override
60      public boolean isCancelled() {
61          return this.cancelled;
62      }
63  
64      @Override
65      public boolean isDone() {
66          return this.completed;
67      }
68  
69      private T getResult() throws ExecutionException {
70          if (this.ex != null) {
71              throw new ExecutionException(this.ex);
72          }
73          if (cancelled) {
74              throw new CancellationException();
75          }
76          return this.result;
77      }
78  
79      @Override
80      public synchronized T get() throws InterruptedException, ExecutionException {
81          while (!this.completed) {
82              wait();
83          }
84          return getResult();
85      }
86  
87      @Override
88      public synchronized T get(final long timeout, final TimeUnit unit)
89              throws InterruptedException, ExecutionException, TimeoutException {
90          Args.notNull(unit, "Time unit");
91          final long msecs = unit.toMillis(timeout);
92          final long startTime = (msecs <= 0) ? 0 : System.currentTimeMillis();
93          long waitTime = msecs;
94          if (this.completed) {
95              return getResult();
96          } else if (waitTime <= 0) {
97              throw new TimeoutException();
98          } else {
99              for (;;) {
100                 wait(waitTime);
101                 if (this.completed) {
102                     return getResult();
103                 } else {
104                     waitTime = msecs - (System.currentTimeMillis() - startTime);
105                     if (waitTime <= 0) {
106                         throw new TimeoutException();
107                     }
108                 }
109             }
110         }
111     }
112 
113     public boolean completed(final T result) {
114         synchronized(this) {
115             if (this.completed) {
116                 return false;
117             }
118             this.completed = true;
119             this.result = result;
120             notifyAll();
121         }
122         if (this.callback != null) {
123             this.callback.completed(result);
124         }
125         return true;
126     }
127 
128     public boolean failed(final Exception exception) {
129         synchronized(this) {
130             if (this.completed) {
131                 return false;
132             }
133             this.completed = true;
134             this.ex = exception;
135             notifyAll();
136         }
137         if (this.callback != null) {
138             this.callback.failed(exception);
139         }
140         return true;
141     }
142 
143     @Override
144     public boolean cancel(final boolean mayInterruptIfRunning) {
145         synchronized(this) {
146             if (this.completed) {
147                 return false;
148             }
149             this.completed = true;
150             this.cancelled = true;
151             notifyAll();
152         }
153         if (this.callback != null) {
154             this.callback.cancelled();
155         }
156         return true;
157     }
158 
159     @Override
160     public boolean cancel() {
161         return cancel(true);
162     }
163 
164 }