Is Future required to perform calculations in a separate thread?

From the documentation

The future is the result of asynchronous computing.

Does this mean that the thread calling the Future # get method should not be the thread that performed the calculations? So, is it advisable for the thread calling Future # get to start the calculation, if it hasn't already? I'm not sure if I can call this asynchronous computing ...

+4
source share
3 answers

" " , . API , ", ". , , .

, , JRE, . , FutureTask :

Callable<String> action = new Callable<String>() {
    public String call() {
        return "hello "+Thread.currentThread();
    }
};

FutureTask<String> ft=new FutureTask<>(action);
ft.run();
System.out.println(ft.get());

FutureTask ExecutorService, , :

ExecutorService runInPlace=new AbstractExecutorService() {
    public void execute(Runnable command) {
        command.run();
    }
    public void shutdown() {}
    public List<Runnable> shutdownNow() { return Collections.emptyList(); }
    public boolean isShutdown() { return false; }
    public boolean isTerminated() { return false; }
    public boolean awaitTermination(long timeout, TimeUnit unit) { return false; }
};
Future<String> f=runInPlace.submit(action);
System.out.println(ft.get());

, execute() :

. , , Executor.

" "...

- ForkJoinTask:

ForkJoinTask<String> fjt=new RecursiveTask<String>() {
    protected String compute() {
        return "hello "+Thread.currentThread();
    }
};
fjt.invoke();
System.out.println(fjt.get());

, , , , . , , .


, get(). , , , get(long timeout, TimeUnit unit). , cancel() .

+3

A Future.get() , , , . , , - .

FutureTask ( , RejectedExecutionHandler), , (Callable ) .

, : , , . , , , (), , , , / ( ).

import java.util.concurrent.*;

public class FutureGetSameThread {

    public static void main(String[] args) {

        // Serial executor with a task-queue 
        // ExecutorService executor = Executors.newSingleThreadExecutor();
        // Serial executor without a task-queue 
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        try {
            Callable<Integer> c = new Callable<Integer>() {
                @Override 
                public Integer call() throws Exception {
                    Thread.sleep(400L); // pretend to be busy
                    return 1;
                }
            };
            final Future<Integer> f = executor.submit(c);
            Callable<Integer> c2 = new Callable<Integer>() {
                @Override 
                public Integer call() throws Exception {
                    // wait for the result from the previous callable and add 1
                    return f.get() + 1;
                }
            };
            Future<Integer> f2 = null;
            try {
                f2 = executor.submit(c2);
                System.out.println("Second callable accepted by executor with task queue.");
            } catch (RejectedExecutionException ree) {
                System.out.println("Second callable rejected by executor without task queue.");
                f2 = new FutureTaskUsingCurrentThread<Integer>(c2);
            }
            Integer result = f2.get();
            System.out.println("Result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdownNow();
        }
    }

    static class FutureTaskUsingCurrentThread<V> extends FutureTask<V> {

        public FutureTaskUsingCurrentThread(Callable<V> callable) {
            super(callable);
        }

        @Override
        public V get() throws InterruptedException, ExecutionException {
            run();
            return super.get();
        }
    }

}
+1

, java.util.concurrent.Future - interface.

, . , , :

  • , ,
  • ,
  • "" .

API future.get() , .

API , , , get(); , "", , "". .

Future executorService.submit(callable).

If your method gets the Future from one of the built-in implementations ExecutorService, then when you call future.get(), you really will wait until another thread returns the result.

+1
source

Source: https://habr.com/ru/post/1609749/


All Articles