Search code examples
javalinuxoopdesign-patternsprocessbuilder

Design optimizations when making external process calls


I need from a java process to call external processes/scripts/cli commands.
Since these calls will be quite a lot and some will return back the result of the process/script that run and others will just run it, I was wondering if:

  1. There is a standard design to build around Java's ProcessBuilder so that I don't have scattered in the code calls to ProcessBuilder constantly
  2. What optimizations can I do? For example would it make sense to read from files all the cli commands instead of keeping them e.g. as final String in the code?

Solution

  • Your question is a little bit vague to write a precise answer but I have some suggestions:

    • Shells are designed to link commands (pipe, wait, and so on) and to code a little bit of logic. Shells are interpreted and are very easy to update but have to keep simple. They may be a basic part of your system.
    • Write your own launch method to start a process and capture stdout and stderr (in two threads), to write a log of your driver.
    • Design an XML file to declaratively specify:
      • the processes paths, theirs arguments (static ones)
      • the parallelism and the synchronization between jobs
    • Write a model in Java to reflect the XML process model (JAXB may be a solution)
    • Add to the model the capability to wait for a set of jobs
    • Add modifiers to the model to dynamically change the value of arguments

    If I try to classify your problem, I think mainly at Control flow.

    To resolve a large problem you may use parallelism: launch concurrently several processes and wait for the termination of all of them: it's a rendez-vous or join phase. You may launch remote command to another networked computer, perhaps.

    A good example to how to specify parallelism into an XML file is ANT build files:

    <parallel>
      <wlrun ... >
      <sequential>
        <sleep seconds="30"/>
        <junit fork="true" forkmode="once" ... >
        <wlstop/>
      </sequential>
    </parallel>
    

    Can I suggest you to use ANT to solve your problem without programming?

    A drawing of wished execution may help, with a paper and a pen... ;-)

    Several graphical applications may help to draw the logical diagram of control flow. Once done, publish it here and you'll obtain more precise answer, I hope...