title: Techniques for modeling a dynamic dataflow with Java concurrency API
body: <p>EDIT: This is basically a "how to properly implement a data flow engine in Java" question, and I feel this cannot be adequately answered in a single answer (it's like asking, "how to properly implement an ORM layer" and getting someone to write out the details of Hibernate or something), so consider this question "closed".</p>
  
  <p>Is there an elegant way to model a dynamic dataflow in Java? By dataflow, I mean there are various types of tasks, and these tasks can be "connected" arbitrarily, such that when a task finishes, successor tasks are executed in parallel using the finished tasks output as input, or when multiple tasks finish, their output is aggregated in a successor task (see <a href="http://en.wikipedia.org/wiki/Flow-based_programming" rel="nofollow noreferrer">flow-based programming</a>). By dynamic, I mean that the type and number of successors tasks when a task finishes depends on the output of that finished task, so for example, task A may spawn task B if it has a certain output, but may spawn task C if has a different output. Another way of putting it is that each task (or set of tasks) is responsible for determining what the next tasks are.</p>
  
  <p>Sample dataflow for rendering a webpage: I have as task types: file downloader, HTML/CSS renderer, HTML parser/DOM builder, image renderer, JavaScript parser, JavaScript interpreter.</p>
  
  <ul>
  <li>File downloader task for HTML file
  
  <ul>
  <li>HTML parser/DOM builder task
  
  <ul>
  <li>File downloader task for each embedded file/link
  
  <ul>
  <li>If image, image renderer</li>
  <li>If external JavaScript, JavaScript parser
  
  <ul>
  <li>JavaScript interpreter</li>
  </ul></li>
  <li>Otherwise, just store in some var/field in HTML parser task</li>
  </ul></li>
  <li>JavaScript parser for each embedded script
  
  <ul>
  <li>JavaScript interpreter</li>
  </ul></li>
  <li>Wait for above tasks to finish, then HTML/CSS renderer (obviously not optimal or perfectly correct, but this is simple)</li>
  </ul></li>
  </ul></li>
  </ul>
  
  <p>I'm not saying the solution needs to be some comprehensive framework (in fact, the closer to the JDK API, the better), and I absolutely don't want something as heavyweight is say Spring Web Flow or some declarative markup or other DSL.</p>
  
  <p>To be more specific, I'm trying to think of a good way to model this in Java with Callables, Executors, ExecutorCompletionServices, and perhaps various synchronizer classes (like Semaphore or CountDownLatch). There are a couple use cases and requirements:</p>
  
  <ol>
  <li>Don't make any assumptions on what executor(s) the tasks will run on. In fact, to simplify, just assume there's only one executor. It can be a fixed thread pool executor, so a naive implementation can result in deadlocks (e.g. imagine a task that submits another task and then blocks until that subtask is finished, and now imagine several of these tasks using up all the threads).</li>
  <li>To simplify, assume that the data is not streamed between tasks (task output->succeeding task input) - the finishing task and succeeding task don't have to exist together, so the input data to the succeeding task will not be changed by the preceeding task (since it's already done).</li>
  <li>There are only a couple operations that the dataflow "engine" should be able to handle:
  
  <ol>
  <li>A mechanism where a task can queue more tasks</li>
  <li>A mechanism whereby a successor task is not queued until all the required input tasks are finished</li>
  <li>A mechanism whereby the main thread (or other threads not managed by the executor) blocks until the flow is finished</li>
  <li>A mechanism whereby the main thread (or other threads not managed by the executor) blocks until certain tasks have finished</li>
  </ol></li>
  <li>Since the dataflow is dynamic (depends on input/state of the task), the activation of these mechanisms should occur within the task code, e.g. the code in a Callable is itself responsible for queueing more Callables.</li>
  <li>The dataflow "internals" should not be exposed to the tasks (Callables) themselves - only the operations listed above should be available to the task.</li>
  <li>Note that the type of the data is not necessarily the same for all tasks, e.g. a file download task may accept a File as input but will output a String.</li>
  <li>If a task throws an uncaught exception (indicating some fatal error requiring all dataflow processing to stop), it must propagate up to the thread that initiated the dataflow as quickly as possible and cancel all tasks (or something fancier like a fatal error handler).</li>
  <li>Tasks should be launched as soon as possible. This along with the previous requirement should preclude simple Future polling + Thread.sleep().</li>
  <li>As a bonus, I would like to dataflow engine itself to perform some action (like logging) every time task is finished or when no has finished in X time since last task has finished. Something like: <code>ExecutorCompletionService&lt;T&gt; ecs; while (hasTasks()) { Future&lt;T&gt; future = ecs.poll(1 minute); some_action_like_logging(); if (future != null) { future.get() ... } ... }</code></li>
  </ol>
  
  <p>Are there straightforward ways to do all this with Java concurrency API? Or if it's going to complex no matter what with what's available in the JDK, is there a lightweight library that satisfies the requirements? I already have a partial solution that fits my particular use case (it cheats in a way, since I'm using two executors, and just so you know, it's not related at all to the web browser example I gave above), but I'd like to see a more general purpose and elegant solution.</p>