Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

I had some Java code that was being code reviewed and it was discovered that a buffered reader did not close the reader. That was the perfect time to use the try-with-resources.

The original code looked like:

/**
     * Retrieves the diagnostic information from the Comscire device.
     * @return String containing the "Status" and "DeviceID" information
     * @throws IOException
     */
    public String getDiagnostics() throws IOException {
        StringBuilder output = new StringBuilder();
        try {
            Process process =
                new ProcessBuilder("/usr/local/bin/diagnostics").start();

            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String data = null;
            boolean done = false;
            while ((data = br.readLine()) != null && !done) {
                if (StringUtils.startsWith(data, "Status") ||
                    StringUtils.startsWith(data, "DeviceID")) {
                    output.append("\t").append(data).append("\n");
                } else if (StringUtils.startsWith(data, "Get 128 Raw Bytes")) {
                    done = true;
                }
            }
        } catch (IOException e) {
            setErrors(true);
            logger.error("Unable to get diagnostics from Comscire process", e);
            throw e;
        }

        return output.toString();
    }

The new code takes advantage of the try-with-resources.

    /**
     * Retrieves the diagnostic information from the Comscire device.
     * @return String containing the "Status" and "DeviceID" information
     * @throws IOException
     */
    public String getDiagnostics() throws IOException {
        StringBuilder output = new StringBuilder();
        try {
            Process process =
                new ProcessBuilder("/usr/local/bin/diagnostics").start();

            try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String data = null;
                boolean done = false;
                while ((data = br.readLine()) != null && !done) {
                    if (StringUtils.startsWith(data, "Status") ||
                        StringUtils.startsWith(data, "DeviceID")) {
                        output.append("\t").append(data).append("\n");
                    } else if (StringUtils.startsWith(data, "Get 128 Raw Bytes")) {
                        done = true;
                    }
                }
            }
        } catch (IOException e) {
            setErrors(true);
            logger.error("Unable to get diagnostics from Comscire process", e);
            throw e;
        }

        return output.toString();
    }

Another case that I had was where an exception was being thrown from within the try-with-resources. Here is what a try-with-resources looks like with an exception.

    /**
     * Fills the integer queue with integers.  Opens the process that calls the USB device, reads the data, splits the
     * CSV into integers and adds them to the queue.  Sets the RNG device to available as it writes integers to the
     * queue.
     * @throws InterruptedException throws if the put operation is interrupted by a timeout
     */
    public void getRandomIntegerData() throws IOException, InterruptedException {
        int queueSize = integerQueue.size();
        try {
            logger.info("Retrieving {} integers from Comscire by calling randint32...",
                        DESIRED_QUEUE_LENGTH - queueSize);
            Process process =
                    new ProcessBuilder("/usr/local/bin/randint32",
                                       Integer.toString(DESIRED_QUEUE_LENGTH - queueSize)).start();

            try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String data = br.readLine();
                for (String stringInt : data.split(",")) {
                    integerQueue.put(Integer.valueOf(stringInt));
                    // check it to ensure that it hasn't been emptied as fast as it could be filled
                    if (integerQueue.size() > 0) {
                        setAvailable(true);
                        setErrors(false);
                    }
                }
            } catch (InterruptedException e) {
                logger.error("Unable to add integers to the Comscire queue", e);
                throw e;
            }
        } catch (IOException e) {
            setErrors(true);
            logger.error("Unable to get integers from Comscire process", e);
            throw e;
        }
    }

January 22nd, 2015

Posted In: Java

Tags: , , ,

Leave a Comment

LinkedIn Auto Publish Powered By : XYZScripts.com