Home > Software engineering >  Could Java Future call its own get() function in its other members?
Could Java Future call its own get() function in its other members?

Time:07-07

I wish to do this:

        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {}
            return 1;
        });
        f1.thenRun(() -> System.out.println(this.get()));

The last line doesn't compile. I just wish to do something inside thenRun function, and prints its own get() result inside it. I don't wish to use this return value outside calls to f1, to make code more tight.

Is there a way to do it?

CodePudding user response:

Try CompletableFuture#thenAccept() where the argument is Consumer<Result>

        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {}
            return 1;
        });
        f1.thenAccept(System.out::println);

CodePudding user response:

this refer to the caller instance(object) who call the instance method, you cannot use this inside a class and refer to the declared cariable f1.

You can test if the task is done then print the result else print another message, giving it 3 seconds to be sure that it will be done for example :

f1.thenRun(() -> {
        try {
            Thread.currentThread().sleep(3000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            if (f1.isDone())
                System.out.println(f1.get());
            else
                System.out.println("Not Done");
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    });
  • Related