Skip to content

Instantly share code, notes, and snippets.

@olim7t
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olim7t/b0e5b7d29618e7aae34f to your computer and use it in GitHub Desktop.
Save olim7t/b0e5b7d29618e7aae34f to your computer and use it in GitHub Desktop.
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Function;
import com.google.common.util.concurrent.*;
public class ListenableFuturesTest {
public static void main(String[] args) throws Exception {
ListeningScheduledExecutorService completer = MoreExecutors.listeningDecorator(
Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("completer").build()));
final SettableFuture<Integer> future = SettableFuture.create();
completer.schedule(new Runnable() {
@Override public void run() {
future.set(1);
}
}, 5, TimeUnit.SECONDS);
ListeningExecutorService transformer = MoreExecutors.listeningDecorator(
Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("transformer").build())
);
Function<Integer, Integer> inc = new Function<Integer, Integer>() {
@Override public Integer apply(Integer n) {
System.out.println("I'm getting executed by " + Thread.currentThread());
return n + 1;
}
};
ListenableFuture<Integer> future1 = Futures.transform(future, inc, transformer);
// Quiz: which thread is this executed on?
ListenableFuture<Integer> future2 = Futures.transform(future1, inc);
future2.get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment