Search code examples
javafxconcurrencyprocessbuilder

Multithreading with a machine and javafx implementation difficulties


I need to build something and I have no idea how. I hope somebody can guide me to the right path or show me how to do it.

I am working with a machine, and this machine produces some output. This output is read through another program. I am reading this output through a process which I created with a process builder in a task. This output needs be processed, and multiple values on the screen must be updated . They all contain a different message, but the message is dependent on the output of the process.

(I need to read the output from a scale, which gives me the weight of the product and the current time. The weight, the current time and the price of the product need to be substracted/calculated from this and need to be displayed on screen).

I can’t use the observer pattern, because then the screen will be updated from another thread, which will trigger an error. I also can’t use updateMessage function of the task and bind a label to the message property because all the labels will have different output.

What could/should I do? Could you please set me on the right track?


Solution

  • You can basically structure it like this:

    Thread machineReadThread = new Thread(() -> {
        boolean finished = false ;
        Process process = null ;
        InputStream in = null ;
        try {
            process = new ProcessBuilder(...).start();
            in = process.getInputStream(); 
            while (! finished) { 
                double weight = readWeightFromStream(in);
                Instant timestamp = readTimestampFromStream(in);
                Platform.runLater(() -> updateUI(weight, timestamp));
                finished = checkFinished();
            }
        } catch (Exception exc) {
            log(exc);
        } finally {
            if (in != null) in.close();
            if (process != null) process.destroy();
        }
    });
    machineReadThread.setDaemon(true);
    machineReadThread.start();