Java – why does the scheduleatfixedrate – schedulewithfixeddelay method not use callable

I'm doing some experiments on Java 8 concurrency

In the scheduledthreadpoolexecutor API

I can see the following two signatures:

schedule(Callable<V> callable,long delay,TimeUnit unit)
schedule(Runnable command,TimeUnit unit)

One for callable and one for runnable

I can also see the following two in the API:

scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)
scheduleWithFixedDelay(Runnable command,TimeUnit unit)

My question is, why don't there be two equivalents of callable

scheduleAtFixedRate(Callable<V> callable,TimeUnit unit)
scheduleWithFixedDelay(Callable<V> callable,TimeUnit unit)

I need to retrieve a boolean result for the operation

thank you.

Solution

What is the return type of scheduleatfixedrate (callable < V >)? The return type of the plan (callable < V >) is future < V >, which means that the value of callable return type V will be available at some time in the future You can wait for this value to be available by calling get () on future

The return type of scheduleatfixedrate (callable < V >) cannot be similar to future < list < V > >, because it means that at some point in the future, all values returned by repeated calls to callable will be available However, there will be more callable scheduled executions, so the list will never exist

For such things, what you need is the concept of asynchronous result flow. You can subscribe to it in such a way that you can process each result when it arrives As far as I know, this does not exist in the standard library A third-party library I know contains Netflix's rxjava For example, using replaysubject in the library, you can create a result stream and process each result on return:

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.TimeUnit;
import rx.subjects.ReplaySubject;

public class Callables {

    public static void main(String[] args) {
        // Example Callable that returns a boolean result
        Random random = new Random();
        Callable<Boolean> callable = () -> random.nextBoolean();

        // Turn the Callable into a Runnable that adds the last result to the stream of results
        ReplaySubject<Boolean> results = ReplaySubject.create();
        Runnable runnable = () -> {
            try {
                boolean result = callable.call();
                results.onNext(result);
            } catch (Exception e) {
                // Needed since Callable can throw an exception,but Runnable cannot
            }
        };

        // Periodically run the Runnable
        scheduledexecutorservice executor = Executors.newScheduledThreadPool(5);
        executor.scheduleAtFixedRate(runnable,1,TimeUnit.SECONDS);

        // Handling the results as they arrive
        results.forEach(result -> System.out.println("Result: " + result));

        System.out.println("Waiting for results...");
    }

}

If you decide to use rxjava, it may be worth using more APIs instead of using executor directly You can use observable Interval generates a stream that emits numbers periodically, and then maps it to call your callable object In this way, you can get the same result flow in a more concise way:

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import rx.Observable;

public class MoreCallables {

    public static void main(String[] args) throws IOException {
        Observable<Long> periodic = Observable.interval(1,TimeUnit.SECONDS);

        Random random = new Random();
        Observable<Boolean> results = periodic.map(i -> random.nextBoolean());

        results.forEach(result -> System.out.println("Result: " + result));

        System.out.println("Waiting for results...");
        system.in.read();
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>