2018年12月16日日曜日

Golangのfake google searchフレームワークをjavaで書いてみた。その2

その1を投稿したあと、某友人から「CompletableFuture使ったらもっとスッキリできるよ」って情報もらった。なので、それ使って書き換えてみた。

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.function.Supplier;

class FakeSearch implements Supplier<String>{
    String name = null;
    public FakeSearch(String name){
        this.name = name;
    }
    @Override    public String get() {
        try {
            Thread.sleep((new Random().nextInt(10) * 1000));
        }catch (Exception e){

        }
        return name;
    }
}

public class CmpGoChannel2 {
    public static void First(Supplier<String> supplier1,Supplier<String> supplier2) throws Exception{
        CompletableFuture<String> future1 =
                CompletableFuture.supplyAsync(supplier1);
        CompletableFuture<String> future2 =
                CompletableFuture.supplyAsync(supplier2);

        CompletableFuture<Object> future3 = CompletableFuture.anyOf(future1, future2);
        System.out.println(future3.get());
    }

    public static void main(String... args) throws Exception{
        FakeSearch web1 = new FakeSearch("Web1");
        FakeSearch web2 = new FakeSearch("Web2");
        FakeSearch image1 = new FakeSearch("Image1");
        FakeSearch image2 = new FakeSearch("Image2");
        FakeSearch video1 = new FakeSearch("Video1");
        FakeSearch video2 = new FakeSearch("Video2");


        CmpGoChannel2 c = new CmpGoChannel2();
        List<Future<String>> list = new ArrayList<>();

        First(web1,web2);
        First(image1,image2);
        First(video1,video2);

    }

}
while(true)と終了フラグで乗り切ってた汚い部分がだいぶきれいになった。

public static void First(Supplier<String> supplier1,Supplier<String> supplier2) throws Exception{
    CompletableFuture<String> future1 =
            CompletableFuture.supplyAsync(supplier1);
    CompletableFuture<String> future2 =
            CompletableFuture.supplyAsync(supplier2);
    CompletableFuture<Object> future3 = CompletableFuture.anyOf(future1, future2);
    System.out.println(future3.get());
}


行数もざっくり60行程度まで収まった。

0 件のコメント:

コメントを投稿