Last active
August 29, 2015 14:09
-
-
Save olim7t/b0e5b7d29618e7aae34f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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