Last active
August 29, 2015 14:18
-
-
Save bassemZohdy/74172a0c3172acfdcff7 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.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Future; | |
import java.util.function.Function; | |
public class FutureFunction<T, R> implements Function<T, Future<R>> { | |
private final Function<T, R> function; | |
private FutureFunction(Function<T, R> function) { | |
this.function = function; | |
} | |
public static <T, R> FutureFunction<T, R> of(Function<T, R> function) { | |
return new FutureFunction<>(function); | |
} | |
@Override | |
public Future<R> apply(T t) { | |
ExecutorService executor = Executors.newSingleThreadExecutor(); | |
Future<R> future = executor.submit( | |
() -> function.apply(t)); | |
executor.shutdown(); | |
return future; | |
} | |
} |
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.ExecutionException; | |
import java.util.concurrent.Future; | |
public class FutureFunctionTest { | |
public static void main(String[] args) throws InterruptedException, ExecutionException { | |
for (int i = 0; i < 1000000; i++) { | |
Future<String> future = FutureFunction.of( | |
FutureFunctionTest::toUpper).apply("hello" + i); | |
System.out.println(future.get()); | |
} | |
} | |
private static String toUpper(String in) { | |
System.out.println(Thread.currentThread().getName()); | |
return in.toUpperCase(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment