Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2009 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.util.concurrent;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
Utilities necessary for working with libraries that supply plain java.util.concurrent.Future instances. Note that, whenver possible, it is strongly preferred to modify those libraries to return ListenableFuture directly.

Author(s):
Sven Mawson
Since:
10.0 (replacing Futures.makeListenable, which existed in 1.0)
 
 public final class JdkFutureAdapters {
  
Assigns a thread to the given java.util.concurrent.Future to provide ListenableFuture functionality.

Warning: If the input future does not already implement ListenableFuture, the returned future will emulate ListenableFuture.addListener(java.lang.Runnable,java.util.concurrent.Executor) by taking a thread from an internal, unbounded pool at the first call to addListener and holding it until the future is done.

Prefer to create ListenableFuture instances with SettableFuture, MoreExecutors.listeningDecorator(java.util.concurrent.ExecutorService), ListenableFutureTask, AbstractFuture, and other utilities over creating plain Future instances to be upgraded to ListenableFuture after the fact.

 
   public static <V> ListenableFuture<V> listenInPoolThread(
       Future<V> future) {
     if (future instanceof ListenableFuture) {
       return (ListenableFuture<V>) future;
     }
     return new ListenableFutureAdapter<V>(future);
   }

  
Submits a blocking task for the given java.util.concurrent.Future to provide ListenableFuture functionality.

Warning: If the input future does not already implement ListenableFuture, the returned future will emulate ListenableFuture.addListener(java.lang.Runnable,java.util.concurrent.Executor) by submitting a task to the given executor at at the first call to addListener. The task must be started by the executor promptly, or else the returned ListenableFuture may fail to work. The task's execution consists of blocking until the input future is done, so each call to this method may claim and hold a thread for an arbitrary length of time. Use of bounded executors or other executors that may fail to execute a task promptly may result in deadlocks.

Prefer to create ListenableFuture instances with SettableFuture, MoreExecutors.listeningDecorator(java.util.concurrent.ExecutorService), ListenableFutureTask, AbstractFuture, and other utilities over creating plain Future instances to be upgraded to ListenableFuture after the fact.

Since:
12.0
 
   public static <V> ListenableFuture<V> listenInPoolThread(
       Future<V> futureExecutor executor) {
     checkNotNull(executor);
     if (future instanceof ListenableFuture) {
       return (ListenableFuture<V>) future;
     }
     return new ListenableFutureAdapter<V>(futureexecutor);
   }

  
An adapter to turn a java.util.concurrent.Future into a ListenableFuture. This will wait on the future to finish, and when it completes, run the listeners. This implementation will wait on the source future indefinitely, so if the source future never completes, the adapter will never complete either.

If the delegate future is interrupted or throws an unexpected unchecked exception, the listeners will not be invoked.

  private static class ListenableFutureAdapter<V> extends ForwardingFuture<V>
      implements ListenableFuture<V> {
    private static final ThreadFactory threadFactory =
        new ThreadFactoryBuilder()
            .setDaemon(true)
            .setNameFormat("ListenableFutureAdapter-thread-%d")
            .build();
    private static final Executor defaultAdapterExecutor =
        Executors.newCachedThreadPool();
    private final Executor adapterExecutor;
    // The execution list to hold our listeners.
    private final ExecutionList executionList = new ExecutionList();
    // This allows us to only start up a thread waiting on the delegate future
    // when the first listener is added.
    private final AtomicBoolean hasListeners = new AtomicBoolean(false);
    // The delegate future.
    private final Future<V> delegate;
    ListenableFutureAdapter(Future<V> delegate) {
      this(delegate);
    }
    ListenableFutureAdapter(Future<V> delegateExecutor adapterExecutor) {
      this. = checkNotNull(delegate);
      this. = checkNotNull(adapterExecutor);
    }
    @Override
    protected Future<V> delegate() {
      return ;
    }
    @Override
    public void addListener(Runnable listenerExecutor exec) {
      .add(listenerexec);
      // When a listener is first added, we run a task that will wait for
      // the delegate to finish, and when it is done will run the listeners.
      if (.compareAndSet(falsetrue)) {
        if (.isDone()) {
          // If the delegate is already done, run the execution list
          // immediately on the current thread.
          .execute();
          return;
        }
        .execute(new Runnable() {
          @Override
          public void run() {
            try {
              .get();
            } catch (Error e) {
              throw e;
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
              // Threads from our private pool are never interrupted.
              throw new AssertionError(e);
            } catch (Throwable e) {
              // ExecutionException / CancellationException / RuntimeException
              // The task is done, run the listeners.
            }
            .execute();
          }
        });
      }
    }
  }
  private JdkFutureAdapters() {}
New to GrepCode? Check out our FAQ X