Callable
Runnable๊ณผ ์ ์ฌํ์ง๋ง Callable์ ๋ฐํ๊ฐ์ ๊ฐ์ง๋๋ค.
Callable
public interface Callable<V> {
V call() throws Exception;
}
Callable์ ์ ์ธํ ๊ฐ์ฒด๋ฅผ ๋ฆฌํดํด ์ค๋๋ค.
Thead์๋ FutureTask
์ ํจ๊ป ์ฌ์ฉํ๊ณ , Executor
์๋ ๊ทธ๋๋ก ์ฌ์ฉํ๋ฉด ๋ฉ๋๋ค
Thread์ด ์์๋๋ฉด Callable์ ์์ ์ ๋ฌ์ ํ๊ณ ์๋ต ๊ฐ์ future๋ futrueTask์ ์ ๋ฌ์ด ๋ฉ๋๋ค.
Main Thread์์ ๊ฐ์ ๊บผ๋ผ๋๋ Callable์์ ๋ฐ์์จ Future&FutureTast์ ์๋ต๊ฐ์ ์ฃผ๊ฒ ๋ฉ๋๋ค.
Thead
public class CallableWithThead implements Callable<String> {
@Override
public String call() throws Exception {
return "I'm Callable";
}
}
public class Main {
public static void main(String[] args) {
FutureTask<String> futureTask = new FutureTask<String>(new CallableWithThead());
Thread thread = new Thread(futureTask);
String result = futureTask.get();
}
}
Executor
public class CallableWithExecutor implements Callable<String> {
@Override
public String call() throws Exception {
return "I'm Callable";
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new CallableWithExecutor());
String result = future.get();
}
}
Improve Future
ํฅ์๋ Future์ CompletableFuture ๊ฐ ์กด์ฌํ๋ค.
runAsnyc : return X supplyAsync : return 0 ๋๊ฐ์ง๋ก ์์ ์ ์คํํ ์ ์๋ค.
public class CallbackSupplier implements Supplier<String> {
@Override
public String get() {
return "I'm Supplier";
}
}
public class CallbackRunnable implements Runnable {
@Override
public void run() {
System.out.println("I'm Runnable");
}
}
public class Main {
public static void main(String[] args) {
CompletableFuture<Void> runAsync = CompletableFuture.runAsync(new CallbackRunnable());
CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(new CallbackSupplier());
Void noResult = runAsync.get();
String result = supplyAsync.get();
}
}
์ถ๊ฐ์ ์ผ๋ก CompleteFuture์๋ thenApply, thenAccept, thenRun์ ์ฌ์ฉํ์ฌ์์ ์ ์ฐ๊ฒฐํด ์ค ์ ์๋ค.
CompletableFuture<Void> runAsync = CompletableFuture.runAsync(new CallbackRunnable())
.thenRunAsync(new CallbackRunnable());
CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(new CallbackSupplier())
.thenApply(s -> s + " and thenApply")
.completeAsync(() -> "I'm completeAsync")
.exceptionallyAsync(throwable -> "I'm exceptionallyAsync");
Void noResult = runAsync.get();
String result = supplyAsync.get();
thenCompose, thenCombine ์ผ๋ก ์์ ์ ์กฐํฉํ ์๋ ์๋ค.
CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(new CallbackSupplier())
.thenCombineAsync(CompletableFuture.supplyAsync(new CallbackSupplier()), (s1, s2) -> s1 + s2)
.thenComposeAsync(s -> CompletableFuture.supplyAsync(() -> s + " and thenComposeAsync"));
์ง๊ธ ๊น์ง์ ๋์ผํ Printer๋ฅผ ์์ ๋ก ์ฌ์ฉ
How do code?
Last updated