Monday, September 17, 2018

async sync

sync와 async

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263// sync
@Test
    public void zipTestSync(){

        long start = System.currentTimeMillis();
      // 비행편 가져오기
        Flight flight = lookupFlight("a");
      // 승객가져오기
        Passenger passenger = findPassanger("person");
      // 티켓 가져오기
        Ticket ticket = getTicket(flight, passenger);
      // 티켓 메일 보내기
        sendEmail(ticket);

        System.out.println(System.currentTimeMillis() - start);
    }

// async
@Test
    public void zipTestSingle(){
        long start = System.currentTimeMillis();

      // 비행기 lazyloading
        Single<Flight> flight = Single.defer(() -> Single.just(lookupFlight("a")))
                .subscribeOn(Schedulers.io());
      // 승객 lazyloading
        Single<Passenger> passenger = Single.defer(() ->Single.just(findPassanger("person")))
                .subscribeOn(Schedulers.io());
      // 비행기에서 승객을 zip으로 묶어서 다 로딩이된후 티켓을 가져오는데 .toBlocking으로 기다린다.
        flight.zipWith(passenger, (f, p) -> getTicket(f, p))
                .toBlocking()
                .value().getFlightName();
        System.out.println(System.currentTimeMillis()- start);

    }

 private Flight lookupFlight(String name) {
        try {
            Thread.currentThread().sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("lokkupFlight : " + name);
        return Flight.builder().name(name).build();
    }

    private Passenger findPassanger(String name){
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("findPassanger");
        return Passenger.builder().name(name).build();
    }

    private Ticket getTicket (Flight flight, Passenger passenger){
        return Ticket.builder().flightName(flight.name).passengerName(passenger.getName()).build();
    }

    private void sendEmail(Ticket ticket){
        System.out.println("sending ");
    }