Java FutureTask Layout

I'm trying to work with the Java types FutureTask, Future, Runnable, Callableand ExecutorService.

What is the best practice for arranging these building blocks?

Given that I have several FutureTask, and I want to execute them sequentially.

Of course, I could do another FutureTask, which sequentially sends / waits for the result for each subtask, but I want to avoid blocking calls.

Another option is to allow these subtasks to call a callback when they are completed and to schedule the next task in the callback. But going down this path, how to create the correct external FutureTask object that also handles exceptions in the subtask without producing most of the template?

Did I miss something?

+5
source share
3 answers

Very important, although not usually described in textbooks:

Runnables to be executed on an ExecutorService should not block. This is because each lock disables the workflow, and if the ExecutorService has a limited number of workflows, there is a risk of a dead end (thread puzzle), and if the ExecutorService has an unlimited number of workflows, then there is a risk that memory runs out. Blocking operations in tasks simply destroy all the benefits of ExecutorService, so use blocking operations only for regular threads.

FutureTask.get()is a lock, so it can be used for regular threads, and not from the ExecutorService task. That is, it cannot serve as a building block, but only to deliver the result of execution to the main stream.

- , , . , , , . , . , , Runnable , ExcutorServices.

( ).

, Akka, , , - .

, https://github.com/rfqu/df4j.

+4

- ScheduledFuture, , . , , ScheduledFuture "". :

    public static final ScheduledExecutorService scheduler = Executors
        .newScheduledThreadPool(1);
    public ScheduledFuture delay = null;

    delay = scheduler.schedule(new Runnable() {
    @Override
    public void run() {
    //do something
    }
    }, 1000, TimeUnit.MILLISECONDS);

    delay = scheduler.schedule(new Runnable() {
    @Override
    public void run() {
    //do something else
    }
    }, 2000, TimeUnit.MILLISECONDS);

, Andy

0

:

  • ExecutorService ( , ).
  • ( ).

, : * Callables ( , ). * .

, :

  • Callables Runnables.
  • Just add what you need to do at the end as the last code inside the task. using Activity.runOnUIThread these final actions should change the GUI.

Normally, you should not actively check when you can send another task or schedule a callback to just send them. The thread queue (blocking if necessary) will handle this for you.

0
source

All Articles