001/* 002 * Copyright (C) 2009 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.util.concurrent; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; 019 020import com.google.common.annotations.Beta; 021import com.google.common.annotations.GwtIncompatible; 022import java.util.concurrent.Executor; 023import java.util.concurrent.Executors; 024import java.util.concurrent.Future; 025import java.util.concurrent.ThreadFactory; 026import java.util.concurrent.atomic.AtomicBoolean; 027import org.checkerframework.checker.nullness.qual.Nullable; 028 029/** 030 * Utilities necessary for working with libraries that supply plain {@link Future} instances. Note 031 * that, whenever possible, it is strongly preferred to modify those libraries to return {@code 032 * ListenableFuture} directly. 033 * 034 * @author Sven Mawson 035 * @since 10.0 (replacing {@code Futures.makeListenable}, which existed in 1.0) 036 */ 037@Beta 038@GwtIncompatible 039@ElementTypesAreNonnullByDefault 040public final class JdkFutureAdapters { 041 /** 042 * Assigns a thread to the given {@link Future} to provide {@link ListenableFuture} functionality. 043 * 044 * <p><b>Warning:</b> If the input future does not already implement {@code ListenableFuture}, the 045 * returned future will emulate {@link ListenableFuture#addListener} by taking a thread from an 046 * internal, unbounded pool at the first call to {@code addListener} and holding it until the 047 * future is {@linkplain Future#isDone() done}. 048 * 049 * <p>Prefer to create {@code ListenableFuture} instances with {@link SettableFuture}, {@link 050 * MoreExecutors#listeningDecorator( java.util.concurrent.ExecutorService)}, {@link 051 * ListenableFutureTask}, {@link AbstractFuture}, and other utilities over creating plain {@code 052 * Future} instances to be upgraded to {@code ListenableFuture} after the fact. 053 */ 054 public static <V extends @Nullable Object> ListenableFuture<V> listenInPoolThread( 055 Future<V> future) { 056 if (future instanceof ListenableFuture) { 057 return (ListenableFuture<V>) future; 058 } 059 return new ListenableFutureAdapter<>(future); 060 } 061 062 /** 063 * Submits a blocking task for the given {@link Future} to provide {@link ListenableFuture} 064 * functionality. 065 * 066 * <p><b>Warning:</b> If the input future does not already implement {@code ListenableFuture}, the 067 * returned future will emulate {@link ListenableFuture#addListener} by submitting a task to the 068 * given executor at the first call to {@code addListener}. The task must be started by the 069 * executor promptly, or else the returned {@code ListenableFuture} may fail to work. The task's 070 * execution consists of blocking until the input future is {@linkplain Future#isDone() done}, so 071 * each call to this method may claim and hold a thread for an arbitrary length of time. Use of 072 * bounded executors or other executors that may fail to execute a task promptly may result in 073 * deadlocks. 074 * 075 * <p>Prefer to create {@code ListenableFuture} instances with {@link SettableFuture}, {@link 076 * MoreExecutors#listeningDecorator( java.util.concurrent.ExecutorService)}, {@link 077 * ListenableFutureTask}, {@link AbstractFuture}, and other utilities over creating plain {@code 078 * Future} instances to be upgraded to {@code ListenableFuture} after the fact. 079 * 080 * @since 12.0 081 */ 082 public static <V extends @Nullable Object> ListenableFuture<V> listenInPoolThread( 083 Future<V> future, Executor executor) { 084 checkNotNull(executor); 085 if (future instanceof ListenableFuture) { 086 return (ListenableFuture<V>) future; 087 } 088 return new ListenableFutureAdapter<>(future, executor); 089 } 090 091 /** 092 * An adapter to turn a {@link Future} into a {@link ListenableFuture}. This will wait on the 093 * future to finish, and when it completes, run the listeners. This implementation will wait on 094 * the source future indefinitely, so if the source future never completes, the adapter will never 095 * complete either. 096 * 097 * <p>If the delegate future is interrupted or throws an unexpected unchecked exception, the 098 * listeners will not be invoked. 099 */ 100 private static class ListenableFutureAdapter<V extends @Nullable Object> 101 extends ForwardingFuture<V> implements ListenableFuture<V> { 102 103 private static final ThreadFactory threadFactory = 104 new ThreadFactoryBuilder() 105 .setDaemon(true) 106 .setNameFormat("ListenableFutureAdapter-thread-%d") 107 .build(); 108 private static final Executor defaultAdapterExecutor = 109 Executors.newCachedThreadPool(threadFactory); 110 111 private final Executor adapterExecutor; 112 113 // The execution list to hold our listeners. 114 private final ExecutionList executionList = new ExecutionList(); 115 116 // This allows us to only start up a thread waiting on the delegate future when the first 117 // listener is added. 118 private final AtomicBoolean hasListeners = new AtomicBoolean(false); 119 120 // The delegate future. 121 private final Future<V> delegate; 122 123 ListenableFutureAdapter(Future<V> delegate) { 124 this(delegate, defaultAdapterExecutor); 125 } 126 127 ListenableFutureAdapter(Future<V> delegate, Executor adapterExecutor) { 128 this.delegate = checkNotNull(delegate); 129 this.adapterExecutor = checkNotNull(adapterExecutor); 130 } 131 132 @Override 133 protected Future<V> delegate() { 134 return delegate; 135 } 136 137 @Override 138 public void addListener(Runnable listener, Executor exec) { 139 executionList.add(listener, exec); 140 141 // When a listener is first added, we run a task that will wait for the delegate to finish, 142 // and when it is done will run the listeners. 143 if (hasListeners.compareAndSet(false, true)) { 144 if (delegate.isDone()) { 145 // If the delegate is already done, run the execution list immediately on the current 146 // thread. 147 executionList.execute(); 148 return; 149 } 150 151 // TODO(lukes): handle RejectedExecutionException 152 adapterExecutor.execute( 153 () -> { 154 try { 155 /* 156 * Threads from our private pool are never interrupted. Threads from a 157 * user-supplied executor might be, but... what can we do? This is another reason 158 * to return a proper ListenableFuture instead of using listenInPoolThread. 159 */ 160 getUninterruptibly(delegate); 161 } catch (Throwable e) { 162 // ExecutionException / CancellationException / RuntimeException / Error 163 // The task is presumably done, run the listeners. 164 } 165 executionList.execute(); 166 }); 167 } 168 } 169 } 170 171 private JdkFutureAdapters() {} 172}