Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  • "hello" 메시지를 받으면 sender() ! "world"로 응답을 보냄

  • ask 패턴(?)을 사용하여 응답을 Future로 받음

  • Await.result로 블로킹 방식으로 응답을 출력



자바

Info

자바7의 java.util.concurrent.Future에 익숙하다면 scala.concurrent.Future가 자바 클래스를 감싼것으로 생각할수도 있지만

실제로는 그렇지 않다. java.util.concurrent.Future 클래스는 폴링을 필요로하며 결과를 얻기위해 블로킹 get 메서드를 사용해야만

한다. 하지만 스칼라의 퓨쳐는 블로킹이나 풀링을 사용하지 않고 함수결과를 조합할수 있으며

JAVA8의 CompletetableFuture<T>가 오히려 여기서 설명하는 퓨쳐와 유사하다.


Erik Meijer의 한마디~

"이보게, 브라이언 괴츠, C#,파이선,자바스크립트는 물론 심지어 PHP도 async, await를 지원하고 있다네. 그런 기능이 없는 언어는 자바일뿐이야.

람다를 이용해서 콜백함수를 사용하면 된다고? 천만에 콜백은 최악이야. 도움이 안된다고. 자바 9 버전에 담으려고 하는 걸 다 내려놓고 지금당장

asymc, await부터 넣으라고. 그래야 모두가 행복해질수 있어"


제대로된 비동기 동시성처리는  Java8부터 지원하기 시작했으며 Java언어 순수스펙에서는  await를 프로그래밍 모델을 지원하지 않기때문에 액터모델의

Ask패턴은 비동기처리 완료인 CompelteableFuture를 이용합니다. 

Code Block
themeEmacs
public class HelloActor extends AbstractActor {

    // 액터 생성 팩토리
    public static Props props() {
        return Props.create(HelloActor.class);
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
            .matchEquals("hello", msg -> {
                getSender().tell("world", getSelf());
            })
            .matchAny(msg -> {
                System.out.println("Unknown message: " + msg);
            })
            .build();
    }
}

public class HelloActorApp {
    public static void main(String[] args) throws Exception {
        ActorSystem system = ActorSystem.create("HelloSystem");

        ActorRef helloActor = system.actorOf(HelloActor.props(), "helloActor");

        // 메시지 보내고 응답 기다리기
        Future<Object> future = Patterns.ask(helloActor, "hello", 5000);
        String result = (String) Await.result(future, Duration.create(5, TimeUnit.SECONDS));

        System.out.println("응답: " + result); // "world"

        system.terminate();
    }
}

...


추가참고자료